Coding, Insights, and Digital Discoveries šŸ‘©šŸ»ā€šŸ’»

From Stay-at-Home Mom to a Developer After 50

Published on

Building Social Share Buttons for My Next.js Blog: A Step-by-Step Journey

ai-automation-wine

Why Social Sharing Matters

Social sharing is a must for any blog looking to expand its reach and boost engagement. Adding social share buttons makes it easy for readers to share content they find valuable with their networks. This organic SEO tool is crucial for building credibility and authority online.

When I started looking into social sharing solutions for my blog, I had two main options in mind.

Exploring the Pre-Built Option

My first stop was ShareThis, a popular platform that lets you easily add social share buttons. ShareThis has several advantages:

  • šŸš€ Quick Setup : Itā€™s ready in minutes.
  • šŸŽØ Design Variety : Plenty of styles and options to match your site.
  • šŸ“Š Built-in Analytics : You get data on shares, which is helpful for tracking engagement.

But there were also downsides that made me hesitate. ShareThis relies on third-party scripts, which can slow down a blogā€™s load time. While itā€™s customizable, the level of control is limited. Plus, since itā€™s an external service, itā€™s vulnerable to potential outages or policy changes that could affect my blog.

Chose a Custom Solution

I decided that, for better performance and control, Iā€™d create my own social share buttons using JavaScript and React Icons. This approach would let me optimize performance, maintain full control, and keep it minimalā€”only including what I really needed. I also wanted a good user experience, so I aimed to build a share modal that would stay accessible as readers scroll through a post.

Building the ShareModal Component

Step 1: Defining the Basic Structure

I started by creating a ShareModal component that renders a share button. When clicked, the button opens a modal with various social media sharing options. Hereā€™s the initial structure:

import { FaFacebook, FaTwitter, FaLinkedin } from "react-icons/fa";

const shareUrls = {
  facebook: `https://www.facebook.com/share.php?u=${encodedLink}`,
  twitter: `http://twitter.com/share?&url=${encodedLink}&text=${encodedMsg}`,
  linkedIn: `https://www.linkedin.com/sharing/share-offsite/?url=${encodedLink}`,
};

const ShareModal = () => (
  <div className="modal">
    <a href={shareUrls.facebook} target="_blank" rel="noopener noreferrer">
      <FaFacebook />
    </a>
    <a href={shareUrls.twitter} target="_blank" rel="noopener noreferrer">
      <FaTwitter />
    </a>
    <a href={shareUrls.linkedin} target="_blank" rel="noopener noreferrer">
      <FaLinkedin />
    </a>
  </div>
);

Step 2: Making the Modal Responsive and Adding Icons

With the basic functionality in place, I made the component responsive for different screen sizes. React Icons made it easy to add consistent, clean-looking icons, and tweaking the modal layout ensured it was accessible on all devices.

Debugging: Handling Issues with Metadata and Image Sharing

With the ShareModal set up, I ran into some platform-specific quirksā€”especially with Facebook and LinkedIn, which werenā€™t displaying the blogā€™s image and title by default. Hereā€™s how I tackled those issues:

  1. Setting Metadata in generateMetadata Function: I double-checked my generateMetadata function in page.tsx (which renders each post) to ensure it included openGraph and twitter properties, so Facebook, Twitter, and LinkedIn could read the necessary information for sharing.

    return {
      title: post.title,
      description: post.summary,
      openGraph: {
        title: post.title,
        description: post.summary,
        url: postUrl,
        images: [{ url: imageUrl }],
      },
      twitter: {
        card: "summary_large_image",
        title: post.title,
        images: [imageUrl],
      },
    };
    
  2. Facebookā€™s fb:app_id Requirement: Although Facebook requires an fb:app_id for integration, itā€™s optional. I created a simple app ID via their developer tools just to avoid any metadata issues.

  3. Using Facebookā€™s and LinkedInā€™s Debugger Tools: To preview how each platform displayed my post, I used Facebookā€™s Sharing Debugger and LinkedInā€™s Post Inspector. These tools are very handy for catching any issues early.

Eventually, the problem came down to a missing / in one of my constructed links within the ShareModal. Oops! Debugging always has its moments, but finding those bugs šŸŖ²šŸž is so satisfying. šŸŽŗ

Step 3: Adding a Fixed Position and Smooth Animation

To keep the ShareModal accessible as readers scroll, I used a custom hook to detect the scroll position, making the modal ā€œstickyā€ once a reader scrolls past a certain point. Hereā€™s how I did it:

const useScrollPosition = () => {
  const [isFixed, setIsFixed] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const scrollY = window.scrollY;
      setIsFixed(scrollY > window.innerHeight * 0.25);
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return isFixed;
};

In the ShareModal component, I used isFixed to toggle between relative and fixed positioning with a smooth animation:

<div className={` ${isFixed ? "fixed top-1/3 left-4 animate-slideLeftIn" : "relative"}`}>

Final Touches and Testing

After adding the sticky positioning and animations, I tested the component across different devices and browsers to make sure it functioned smoothly and looked consistent.

Reflection: The Benefits of a Custom Social Sharing Solution

Building a custom social sharing feature turned out to be a fun journey that took me about two hours, and it was incredibly rewarding. Hereā€™s what I loved about the custom approach:

  • āš” Better Performance : Without external scripts, my site stays fast and responsive.
  • šŸŽ›ļø Complete Control : I could tweak every detail to align with my blogā€™s needs.
  • šŸ§¹ Less Bloat : I kept the code minimal, using only what was necessary, which is impossible with many pre-built plugins.

This experience reminded me that sometimes, the best solutions are the ones you create yourself. Iā€™m excited to keep building features that make my blog more engaging and user-friendly, and I canā€™t wait to see how readers respond to these custom share buttons. šŸ’“šŸ’“


ā† See All Posts