react helmet tutorials with examples


React Helmet is an npm library provides react components to change and updates tags values inside head tag of an html in react pages.

Head is an parent tag for title, meta,script,link, noscript and style tag, So you can change or set this tags values dynamically.

This tutorial covers an basic react-helmet package, how to change document head values dynamically, How it is useful in SEO during server side rendering.

Why it is required and what are advantages?

In Index.html, you can set basic head child as you seen below

public/index.html

<head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="react descript" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <title>React title</title>
</head>

This is Main component for your react pages. Any component you created will be render as a child component of main component ie App.js.

you can ovverrides with parent components with child components values dynamically using helmet component.

It helps to override and update dynamically the child elements inside an head tags, This is very useful to have a clean SEO for crawlers about each page in Single page applications.

Some important features

  • Can be changed all tags - title, meta,script,link,noscript and style tag
  • It is easily integrated into server side and client side rendering

Installation

First, install library with npm or yarn command to existing react application

yarn add react-helmet
npm install react-helmet

Changing html head childers using react-helmet example

Helmet is an component which can dynamically change document head attributes values dynamcially

import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

class AddingScriptExample extends Component {


    render() {
        return (
            <div className="application">
                <Helmet>
                    <base />
                    <title>React helmet example</title>
                    <meta name="description" content="React helment is useful for seo for dynamically changing head information" />
                    <link rel="canonical" href="somelink" />

                    <script type="text/javascript">
                        alert('react component script');
                    </script>
                </Helmet>
            ...
            </div>
        );
    }
}
export default AddingScriptExample;

You can inspect these meta tags on view source option of your webpage.

react-helmet npm example link,title,meta adding

Following are the attributes can be changed dynamically with helmet component

base - base path of the page meta - metadata information about webpage, these can have attribute types robots,description,keywords link - Adding external styles script -This can add inline script as well as external javascript files.

Note: if there is any issue with overriding tag values dynamically, try to add data-react-helmet=true to tags inside helemet component.

How to load inline and external Script tag

if you want to add custom JavaScript to react component, You can add the following line of code.

script tag with type="text/javascript” to be defined inside helmet component

<helmet>
 <script type="text/javascript">
        alert('react component script');
</script>
</helmet>

Adding script custom urls , we can do with script url syntax as discussed [here]

How to do you document title in reacat component

We can use PureComponent instead of Component as there is not state or props changes required and do shallow comparison of scalar values and object references, Thus improves performance on loading components.

import React from 'react'
import { Helmet } from 'react-helmet'

class DocumentTitle extends React.PureComponent {
    render() {
        return (
            <>
                <Helmet>
                    <title>About us</title>
                </Helmet>

            </>
        )
    }
}
export default DocumentTitle;

react-helmet-async example

helmet component is synchronous and works perfectly on client side rendering,

It causes an issues on server side while streaming component with ignoring react side effects.

react-helmet-async requires provider to capture the helmet component state of DOM tree in react application.

Async usage is same as like helmet component expect by adding component inside HelmetProvider component.

You can also use renderToString in Server side rendering for better usage.

import Helmet, { HelmetProvider } from "react-helmet-async";


class HelmentAsyncExample extends Component {
    render() {
        return (

            <HelmetProvider>
                <div >
                    <Helmet>
                        <title>React Helmet Asyc example</title>
                        <link rel="canonical" href="https://www.url.com/" />
                        <meta keywords=" seo keywords" />
                        <meta description=" website description" />

                    </Helmet>
                </div>
            </HelmetProvider>
        )
    }
}
export default HelmentAsyncExample;

server side rendering example

On server side, Call Helmet.renderStatic() method to get document header tags values during prerender process.

Here is component example code:

import React from 'react';
import { renderToString } from 'react-dom/server';
import express from 'express';
import App from './src/App';
import { Helmet } from 'react-helmet';
const expressServer = express();


expressServer.get('/*', (req, res) => {
    const appRender = renderToString(<App />);
    const helmet = Helmet.renderStatic();

    res.send(stringHtml(appRender, helmet));
});

expressServer.listen(4000);

function stringHtml(appStr, helmet) {
    return `
    <!doctype html>
    <html ${helmet.htmlAttributes.toString()}>
        <head>
            ${helmet.title.toString()}
            ${helmet.meta.toString()}
            ${helmet.link.toString()}
        </head>
        <body ${helmet.bodyAttributes.toString()}>
            <div id="container">
              // react component code can be added
            </div>
        </body>
    </html>
  `
}

Advantages

  • Added the tags dynamically in single page applications and improves Search engine optimization of each page
  • Helps crawlers and search engine bots for understanding the page
  • If there are multiple meta tags with different values in react tree components, child component overrides the parent
Similar Posts