Skip to main content

Adding share buttons on blog posts

4 Apr 2023 · Last updated: 10 Apr 2023 ·
Posted in weblog#tech

Rather than relying on pre-built widgets or SDKs from platforms like Twitter, there is a simpler approach to adding "Share on <site>" links to your blog posts using URL redirection.

Most sites have a dedicated "submit" link that allows for specific query parameters to be used in order to pre-populate the URL and title. The parameter names may differ for each site, for example, for Twitter it would be https://twitter.com/intent/tweet?text=some text&url=https://example.org.

You can store these values for different sites in an array of objects and map through it to display a link with the target attribute set to _blank. These links can then be styled with CSS without loading any external scripts.

const shareSites = [
  {
    name: 'Hacker News',
    submitUrl: 'https://news.ycombinator.com/submitlink',
    titleParam: 't',
    urlParam: 'u',
  },
  {
    name: 'Lobsters',
    submitUrl: 'https://lobste.rs/stories/new',
    titleParam: 'title',
    urlParam: 'url',
  },
  {
    name: 'Reddit',
    submitUrl: 'https://reddit.com/submit',
    titleParam: 'title',
    urlParam: 'url',
  },
  {
    name: 'Twitter',
    submitUrl: 'https://twitter.com/intent/tweet',
    titleParam: 'text',
    urlParam: 'url',
  },
]

// Later in the post template component
const title = "How to ..."
const permalink = "https://example.com/..."
...
<div className="share-buttons">
  Share this post on:
  {shareSites.map((site) => (
    <span key={site.name}>
      <a
        href={`${site.submitUrl}
        ?${site.titleParam}=${encodeURIComponent(title)}
        &${site.urlParam}=${encodeURIComponent(permalink)}`}
        target="_blank"
        rel="noopener noreferrer"
      >
        {site.name}
      </a>{" "}
    </span>
  ))}
</div>