Code for Heaven

Go to the home page

My Gatsby Helmet - tags for Facebook's Open Graph

Helmet is a useful plugin for React/Gatsby which lets you control your document's head. If you haven't heard about it already, I strongly suggest you visiting the plugin's website. In this article, I'm going to share with you, how I turned it into a reusable component, that suits well to my blog needs.

And here it is:

export default function MyHelmet({ data }) {
    const {
        description = "",
        domain = "",
        externalScriptsUrls = [],
        facebookThumbnail = "",
        title = "",
        slug = "",
    } = data;

    return (
        <title>{title} - Code for Heaven</title>

        <link rel="canonical" href={`${domain}/${slug}`} />

        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />

        <meta property="og:description" content={description} />
        <meta property="og:title" content={title + " - Code for Heaven"} />
        <meta property="og:type" content="article" />
        {slug === ""
          ? <meta property="og:url" content={`${domain}/`} />
          : <meta property="og:url" content={`${domain}/${slug}/`} />
          ? <meta property="og:image" content={`${domain}${facebookThumbnail}`} />
          : ""}
        <meta property="og:image:width" content="1200" />
        <meta property="og:image:height" content="630" />
        { => <script async src={url}></script>)}

Running from the top. You can see simple destructuring of a data object, that was passed to MyHelmet element. For my purposes, I need properties, I will use to set values of open graph meta tags. Open graph meta tags are super-useful as they describe how a page will look like when posted on Facebook.

Properties I included are the most basic and verified by Facebook's sharing debugger. If you, like me, are building your website from scratch, make sure to put them into all pages <head> sections.

The benefits of these solutions are that I don't need to repeat strings, like my blog's domain. It proved its value when I added SSL to the domain and I only had to change it once.

How would you change this snippet? What would you improve? Let me know and make sure to come back, as I expect myself to work on it further.

Enjoyed it? Great! Let's stay in touch.