Does React Helmet help Facebook to see your OG meta tags?
The crawler that takes less than single or two seconds cannot find the head tags that are added by React Helmet. You might have also noticed that there is a delay in updating meta tags when you render a page that updates these tags dynamically when it expects data from an API call. This makes meta tags and other head tags not available to Facebook, Twitter and other social media and also to some search engines.
As Dan Abramov says,
react-helmet won’t make Facebook see your og tags if you only use it on the client.
The above statement is valid. But if helmet is implemented with SSR, you can get rid of this issue. Here’s the explanation.
What is React Helmet?
React Helmet is a simple reusable component that makes it easy to manage and dynamically change the tags inside the head tag of a document. For instance, you can use React Helmet
to set Open Graph
(OG) tags, description, meta tags and other head tags on the DOM.
How to install?
The installation is very simple, below commands will install helmet within a minute or less.
Yarn:
yarn add react-helmet
npm:
npm install --save react-helmet
How to use?
Just import Helmet
from react-helmet
module and start implementing your head scripts.
1 2 |
import React from "react"; import {Helmet} from "react-helmet"; |
Does it allow server-side rendering (SSR)?
Yes. The newer version of React allows SSR. To use on the server, call Helmet.renderStatic()
after
1 |
ReactDOMServer.renderToString() |
OR
1 |
ReactDOMServer.renderToStaticMarkup() |
to get the head tags for use in your pre-rendered document.
Because this component keeps track of mounted instances, you have to make sure to call renderStatic on the server. Otherwise, it may lead to a memory leak.
1 2 |
ReactDOMServer.renderToString(<Handler />); const helmet = Helmet.renderStatic(); |
You can use it in two scenarios.
For output as a string representation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const html = ` <!doctype html> <html ${helmet.htmlAttributes.toString()}> <head> ${helmet.title.toString()} ${helmet.meta.toString()} ${helmet.link.toString()} </head> <body ${helmet.bodyAttributes.toString()}> <div id="content"> // React stuff here </div> </body> </html> `; |
For output as a React component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function HTML () { const htmlAttrs = helmet.htmlAttributes.toComponent(); const bodyAttrs = helmet.bodyAttributes.toComponent(); return ( <html {...htmlAttrs}> <head> {helmet.title.toComponent()} {helmet.meta.toComponent()} {helmet.link.toComponent()} </head> <body {...bodyAttrs}> <div id="content"> // React stuff here </div> </body> </html> ); } |
Just import the react-helmet
instance from the app on the server.
Here is the GitHub link for React Helmet.
Recent Comments