Ciprian Craciun - FrontEnd Developer

Ciprian Craciun

FrontEnd/Web Developer

Engineering is about making a product better, learning from past mistakes and create a process which is easy for all to understand.

Generate meta tags in react js for sharing

If you are building websites using react js with create-react-app it’s great but we have a problem with meta tags.

Suppose you have a blog on your react js web application and you want to share your article to get more visibility, the problem is Facebook, LinkedIn and Twitter don’t recognize your meta tags because of your static index.html from the build.

In order to have a great preview when you share an article, Facebook and LinkedIn need to have in the header of the page open graph meta tags:

<meta property="og:title" content="" />
<meta property="og:url" content="" />
<meta property="og:type" content="article" />
<meta property="og:description" content="" />
<meta property="og:image" content="" />

For Twitter we need to have another set of meta tags:

<meta property="twitter:title" content="" />
<meta property="twitter:description" content="" />
<meta property="twitter:image" content="" />
<meta property="twitter:card" content="" />

After the above meta tags are present in your article you can check how the preview share will look using the official debuggers: Facebook debugger, Linkedin debugger, and Twitter debugger.

How to fix meta tags in our react js app?

The only good solution would be to serve those meta tags server-side. As the official documentation suggests you can place some placeholders in the index.html file and every time you change the page the server would fill those placeholders with the right words, as an example, meta tags should look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta property="og:title" content="__OG_TITLE__" />
 <meta property="og:description" content="__OG_DESCRIPTION__" />
 <meta property="og:url" content="__OG_URL__" />
 <meta property="og:image" content="__OG_IMAGE__" />
</head>
</html>

Use an external library

There is a lot of discussions about using react-helmet, yes is very easy to use and to update your meta tags from a component instead of changing from index.html file.

Depends on the content of your website and what purpose should serve, in my case because i worked on a blog website the best solution was to serve those tags from the server.

Don’t forget to use those official tools from Facebook, LinkedIn, and Twitter they help a lot.

If you like what I suggested here you can follow me on Twitter or subscribe to my newsletter.

You may be also interested in:

Sharing is caring!


Leave a Reply

Your email address will not be published. Required fields are marked *