SHARE

How to Code a Social Share Button with Material UI

Step-by-step guide of how to create a dropdown share button for all of the top social media sites with Material-UI

Profile Pic of Snappy Web Design

Jun 8 · 15 min read

How to Code a Social Share Button with Material UI

Social share buttons are a must-have element of every website with a blog or article outlet. Social share buttons allow users to spread the word about your content by posting links which turn in to backlinks for your site and boost your SEO.

See final codesandbox below ⬇️

Top 30 Ways to Create Backlinks According to Reddit


Setup - Dependencies

We'll be making use of some great packages and libraries to make the process much easier. You can find each of them along with links to their installation guides below:

Step #1 - The Button (Boilerplate)

First, we need a button that has a Popper which displays onClick. Luckily, Material-UI's extensive documentation has some boilerplate code which we can use for our purposes. It looks like this:

boilerplate

With some creative liberties taken on my part, we have our initial button and popper. It looks like this:

step1 button popper (1)

and our code thus far looks like this:

import React from "react" import { FaRegShareSquare } from "react-icons/fa" import { makeStyles } from "@material-ui/core/styles" import Typography from "@material-ui/core/Typography" import Button from "@material-ui/core/Button" import Popper from "@material-ui/core/Popper" import PopupState, { bindToggle, bindPopper } from "material-ui-popup-state" import Fade from "@material-ui/core/Fade" import Paper from "@material-ui/core/Paper" import { fade } from "@material-ui/core/styles/colorManipulator" const useStyles = makeStyles(theme => ({ typography: { padding: theme.spacing(2) }, btn: { backgroundColor: "#26a27b", color: "rgba(255,255,255,0.9)", fontWeight: 500, "&:hover": { backgroundColor: fade("#26a27b", 0.9085) } } })) export default function DropdownShareButton() { const classes = useStyles() return ( <PopupState variant="popper" popupId="demo-popup-popper"> {popupState => ( <div> <Button className={classes.btn} color="inherit" {...bindToggle(popupState)} > <FaRegShareSquare /> Share Article </Button> <Popper {...bindPopper(popupState)} transition> {({ TransitionProps }) => ( <Fade {...TransitionProps} timeout={350}> <Paper> <Typography className={classes.typography}> The content of the Popper. </Typography> </Paper> </Fade> )} </Popper> </div> )} </PopupState> ) }

Step #2 - Styling The Social Links

Next, we want to replace the text that says "The content of the Popper" with our list containing the Icons and Titles for our social media platforms. For this example, those are Facebook, Twitter, and Reddit. We'll also have an option to "Copy Link to Clipboard" so that users can easily share the article via email, IM, or their preferred social media platform.

step 2 list and icons (1)

Here's the code that we added:

Note that we give each <ListItem> an id of the corresponding service ('reddit', 'twitter', 'reddit', 'copy'). This is necessary for the next step.

// https://material-ui.com/components/lists/#lists import List from '@material-ui/core/List' import ListItem from '@material-ui/core/ListItem' import ListItemIcon from '@material-ui/core/ListItemIcon' import ListItemText from '@material-ui/core/ListItemText' import FacebookIcon from '@material-ui/icons/Facebook' import TwitterIcon from '@material-ui/icons/Twitter' import RedditIcon from '@material-ui/icons/Reddit' import LinkIcon from '@material-ui/icons/Link' <List dense={true} className={classes.paper}> <ListItem button id='facebook' > <ListItemIcon> <FacebookIcon /> </ListItemIcon> <ListItemText primary='Facebook' /> </ListItem> <ListItem button id='twitter'> <ListItemIcon> <TwitterIcon /> </ListItemIcon> <ListItemText primary='Twitter' /> </ListItem> <ListItem button id='reddit'> <ListItemIcon> <RedditIcon /> </ListItemIcon> <ListItemText primary='Reddit' /> </ListItem> <ListItem button id='copy'> <ListItemIcon> <LinkIcon /> </ListItemIcon> <ListItemText primary='Copy Link' /> </ListItem> </List>

Step #3 - The Switch Statement (onClick Handler)

Now for the good part - where we actually open the link to share the article in the clients browser.

These are the social share/api share links we'll be using:

In order to copy the link to the clipboard, we just need to use this line of javascript: navigator.clipboard.writeText('https://your.site')

Since we assigned each ListItem a corresponding ID in Step 2, our javascript switch statement is very straightforward. We want to:

  • Identify which platform the user wants to share the link through
    • (which we'll do with the event.currentTarget.id)
  • Encode the link to make it readable to servers, if the platform requires it
  • Open the link on the clients browser

It looks like this:

const handleShare = (e) => { e.preventDefault() const ahref = window.location.href const encodedAhref = encodeURIComponent(ahref) var link switch (e.currentTarget.id) { case 'facebook': link = `https://www.facebook.com/sharer/sharer.php?u=${ahref}` open(link) break case 'twitter': link = `https://twitter.com/intent/tweet?url=${encodedAhref}` open(link) break case 'reddit': link = `https://www.reddit.com/submit?url=${encodedAhref}` open(link) break case 'copy': navigator.clipboard.writeText(ahref) break default: break } } const open = (socialLink) => { window.open(socialLink, '_blank') }

Now all that's left to do is add an onClick to each ListItem with an id. The onClick will look like: onClick={handleShare}


That's IT! You're done! It's as simple as that

That's literally all it takes to code a social share button with material-ui, thanks to a number of helpful utilities and packages.

Here's the final product! voila

Screenshot 2021-06-08 231454


import React from "react" import { FaRegShareSquare } from "react-icons/fa" import List from "@material-ui/core/List" import ListItem from "@material-ui/core/ListItem" import ListItemIcon from "@material-ui/core/ListItemIcon" import ListItemText from "@material-ui/core/ListItemText" import { makeStyles } from "@material-ui/core/styles" import Button from "@material-ui/core/Button" import Popper from "@material-ui/core/Popper" import PopupState, { bindToggle, bindPopper } from "material-ui-popup-state" import Fade from "@material-ui/core/Fade" import Paper from "@material-ui/core/Paper" import { fade } from "@material-ui/core/styles/colorManipulator" import FacebookIcon from "@material-ui/icons/Facebook" import TwitterIcon from "@material-ui/icons/Twitter" import RedditIcon from "@material-ui/icons/Reddit" import LinkIcon from "@material-ui/icons/Link" const useStyles = makeStyles(theme => ({ typography: { padding: theme.spacing(2) }, btn: { backgroundColor: "#26a27b", color: "rgba(255,255,255,0.9)", fontWeight: 500, "&:hover": { backgroundColor: fade("#26a27b", 0.9085) } } })) export default function DropdownShareButton() { const classes = useStyles() const handleShare = e => { e.preventDefault() const ahref = window.location.href const encodedAhref = encodeURIComponent(ahref) var link switch (e.currentTarget.id) { case "facebook": link = `https://www.facebook.com/sharer/sharer.php?u=${ahref}` open(link) break case "twitter": link = `https://twitter.com/intent/tweet?url=${encodedAhref}` open(link) break case "reddit": link = `https://www.reddit.com/submit?url=${encodedAhref}` open(link) break case "copy": navigator.clipboard.writeText(ahref) break default: break } } const open = socialLink => { window.open(socialLink, "_blank") } return ( <PopupState variant="popper" popupId="demo-popup-popper"> {popupState => ( <div> <Button className={classes.btn} color="inherit" {...bindToggle(popupState)} > <FaRegShareSquare /> Share Article </Button> <Popper {...bindPopper(popupState)} transition> {({ TransitionProps }) => ( <Fade {...TransitionProps} timeout={350}> <Paper> <List dense={true} className={classes.paper}> <ListItem button id="facebook" onClick={handleShare} > <ListItemIcon> <FacebookIcon /> </ListItemIcon> <ListItemText primary="Facebook" /> </ListItem> <ListItem button id="twitter" onClick={handleShare} > <ListItemIcon> <TwitterIcon /> </ListItemIcon> <ListItemText primary="Twitter" /> </ListItem> <ListItem button id="reddit" onClick={handleShare} > <ListItemIcon> <RedditIcon /> </ListItemIcon> <ListItemText primary="Reddit" /> </ListItem> <ListItem button id="copy" onClick={handleShare} > <ListItemIcon> <LinkIcon /> </ListItemIcon> <ListItemText primary="Copy Link" /> </ListItem> </List> </Paper> </Fade> )} </Popper> </div> )} </PopupState> ) }

Bonus Section: Extending The Example

Looking to expand your horizons and test your skills? Lucky you! There are a number of enhancements that you can easily make to this code. Set yourself up with the demo codesandbox and the Material-UI documentation and try coding the following features:

  1. Utilize a Snackbar to display a success alert to the user when they click "Copy Link"
  2. Utilize a ClickAwayListener to close the Popper when the user clicks outside of it
  3. Utilize javascript to close the Popper after the user has clicked a ListItem
  4. Utilize the Hidden component to hide the "Copy Link" ListItem on mobile devices (due to compatibility of the navigator.clipboard.writeText function)
Hire me

More from Snappy Web Design

Subscribe to the Snappy Web Design Blog to get notified when a new post goes live. We'll never share your e-mail address or use it for any reason other than to share new posts.

Copyright © 2024. Snappy Web Design. All rights reserved.