How to dynamically set Meta Title Tag in React

#react #react-helmet

Last updated on Sep 6, 2020 by Suraj Sharma



In this tutorial, you learn how you can dynamically set a page meta title tag from your React components.

There are a few libraries that do this job very effectively and are being widely used among the React community.

In this tutorial, we are going to use react-helmet for dynamically setting a page meta title tag.



Getting started


Install react-helmet


npm install --save react-helmet

Let’s consider two components: Home and About components, which are route to '/home' and '/about' respectively.

We are going to create a third component MetaTitle.


// MetaTitle.jsx

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

const MetaTitle = (props) => {
  return (
    <>
      <Helmet>
        <title>{props.title ? `${props.title}` : 'No Title'}</title>
      </Helmet>
    </>
  )
}

export default MetaTitle;

This component contains the logic to dynamically set the Meta title tag.

We have passed the title as one of the props to the MetaTitle component, which we set in Home and About components.


// Home.jsx

import React from 'react';
import MetaTitle from './MetaTitle';

const Home = () => {
  return (
    <>
      <MetaTitle title="Home Page" />
      <div>
        Home Page
      </div>
    </>
  )
}

export default Home;


//About.jsx

import React from 'react';
import MetaTitle from './MetaTitle';
const About = () => {
  return (
    <>
      <MetaTitle title="About Page" />
      <div>
        About page
      </div>
    </>
  )
}

export default About;

There is one more React library to set the Meta title tag, that is react-meta-tags. However, It is not actively maintained by the contributors, last commit was pushed on 15 Feb, 2019.



Conclusion


This tutorial demonstrates how you can set Meta title tag with react-helmet. However you can modify the MetaTitle component to dynamically update other Meta description tags.



Related Articles



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.