DEV Community

Cover image for Create a Share Button for Social Media Links in React (Without Any Package) ๐Ÿ“ค
Sarwar Hossain
Sarwar Hossain

Posted on

15

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 Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Googleโ€™s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn 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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay