DEV Community

Cover image for Create a Share Button for Social Media Links in React (Without Any Package) 📤
Sarwar Hossain
Sarwar Hossain

Posted on

13

Create a Share Button for Social Media Links in React (Without Any Package) 📤

Sharing your content on social media directly from your React app to WhatsApp, Messenger, Twitter, and LinkedIn, without using any third-party packages. 📱💻

🌟 Core Idea

  1. Opens a new tab for each social media platform with a pre-filled message containing text and a URL.
  2. Uses native Clipboard API to allow users to copy the link.
  3. Avoids the complexity of installing additional npm packages for social sharing.
  4. Re usable react component.

💻 Let's Dive into the Code:


import React, { useState } from "react";
import {
  FaWhatsapp,
  FaFacebookMessenger,
  FaTwitter,
  FaLinkedin,
  FaRegClipboard,
  FaClipboardCheck,
  FaShare,
} from "react-icons/fa";

const ShareButton = ({ text, url }) => {
  const [shareNow, setShareNow] = useState(false);
  const message = encodeURIComponent(`${text} ${url}`);

  // Social media share handlers
  const handleWhatsAppShare = () => {
    window.open(`https://wa.me/?text=${message}`, "_blank");
  };

  const handleMessengerShare = () => {
    window.open(
      `fb-messenger://share/?link=${encodeURIComponent(url)}&app_id=YOUR_APP_ID`,
      "_blank"
    );
  };

  const handleTwitterShare = () => {
    window.open(`https://twitter.com/intent/tweet?text=${message}`, "_blank");
  };

  const handleLinkedInShare = () => {
    window.open(
      `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(
        url
      )}`,
      "_blank"
    );
  };

  // Clipboard functionality
  const [copied, setCopied] = useState(false);
  const handleCopy = () => {
    navigator.clipboard.writeText(url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    });
  };

  return (
    <div>
      {/* Main Share Button */}
      <button
        className="px-3 py-1 text-white rounded-md flex gap-1 bg-blue-400 font-semibold mx-auto"
        onClick={() => setShareNow(!shareNow)}
      >
        <span> Share {!shareNow && <span> Now </span>} </span>
        <FaShare size={24} />
      </button>

      {/* Share Options Section */}
      {shareNow && (
        <section className="my-2">
          <div className="flex flex-col items-center justify-center bg-gray-100 py-2 ">
            <h1 className="text-2xl font-bold mb-4">Share this content</h1>
            <div className="flex space-x-4 py-3">
              <button
                onClick={handleWhatsAppShare}
                className="flex items-center justify-center p-2 bg-green-500 text-white rounded-full hover:bg-green-600"
              >
                <FaWhatsapp size={24} />
              </button>
              <button
                onClick={handleMessengerShare}
                className="flex items-center justify-center p-2 bg-blue-500 text-white rounded-full hover:bg-blue-600"
              >
                <FaFacebookMessenger size={24} />
              </button>
              <button
                onClick={handleTwitterShare}
                className="flex items-center justify-center p-2 bg-blue-400 text-white rounded-full hover:bg-blue-500"
              >
                <FaTwitter size={24} />
              </button>
              <button
                onClick={handleLinkedInShare}
                className="flex items-center justify-center p-2 bg-blue-700 text-white rounded-full hover:bg-blue-800"
              >
                <FaLinkedin size={24} />
              </button>
            </div>
          </div>

          {/* Copy URL Section */}
          <div className="flex flex-col items-center justify-center bg-gray-100 mb-2 py-2">
            <h1 className="text-xl font-bold mb-4">Copy this URL</h1>
            <div className="flex items-center justify-center">
              <button
                onClick={handleCopy}
                className={`flex items-center justify-center p-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition duration-200 ${
                  copied ? "bg-green-600 hover:bg-green-700" : ""
                }`}
              >
                {copied ? (
                  <FaClipboardCheck size={24} />
                ) : (
                  <FaRegClipboard size={16} />
                )}
                <span className="ml-2">{copied ? "Copied!" : "Copy URL"}</span>
              </button>
            </div>
          </div>
        </section>
      )}
    </div>
  );
};

export default ShareButton;


Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (3)

Collapse
 
it_huy_31341981602a5f0ef1 profile image
IT Huy •

Thanks

Collapse
 
ta_emon profile image
Tanvir Ahmed Emon •

It's working! Great👌

Collapse
 
sarwarasik profile image
Sarwar Hossain •

Thanks bro

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up