DEV Community

Craciun Ciprian
Craciun Ciprian

Posted on

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 doesn't recognize your meta tags because of your index.html file 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="" />
Enter fullscreen mode Exit fullscreen mode

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="" />
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 the 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 meta 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.

The original article can be found on my blog

Top comments (1)

Collapse
 
thebuddysystem profile image
thebuddysystem

The Twitter debugger link is the same as the facebook one.