What is the purpose of react-helmet?

PBandJen picture PBandJen · Oct 7, 2018 · Viewed 50.4k times · Source

I've created a server-side react app, where it would return html as shown below:

const html = renderToString(<App />);
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <title>A Cool Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
  <body>
    <div id="root">${html}</div>
    <script src="${ROOT}/client-bundle.js"></script>
  </body>
</html>

I read a lot of people have been using react-helmet to manage the content in head. I'm wondering what's the benefit of using it, when I can just directly include as shown above.

Answer

Lexis Hanson picture Lexis Hanson · Oct 7, 2018

A major benefit or react-helmet is when you have multiple components in a tree with <head> tags, and you have <meta> tags with the same attributes/values.

For instance, if on your index page component you have:

const html = renderToString(<App />);
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="This is the index page description"> 
    <title>A Cool Index Page</title>
  </head>
</html>

But then on a leaf page component, you also have a <head> tag containing meta tags:

<html>
  <head>
    <meta name="description" name="This is the unique leaf page description"> 
    <title>A Cool Leaf Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
</html>

Notice between our two page components there are two meta tags with the same attribute value name="description" in our tree. You might think this could lead to duplication, but react-helmet takes care of this problem.

If someone ends up on the leaf page, react-helmet overrides the index/site-level description meta tag and renders the lower-level one, the one specifically for the leaf page.

It will also contain the viewport meta tag, since it did not have to be overwritten.

Because of react-helmet, on the leaf page, the <head> would appear as follows:

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" name="This is the unique leaf page description"> 
    <title>A Cool Leaf Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
</html>