How to update meta tags in React.js?

Reactjs

Reactjs Problem Overview


I was working on a single page application in react.js, so what is the best way to update meta tags on page transitions or browser back/forward?

Reactjs Solutions


Solution 1 - Reactjs

I've used react-document-meta in an older project.

Just define your meta values

const meta = {
    title: 'Some Meta Title',
    description: 'I am a description, and I can create multiple tags',
    canonical: 'http://example.com/path/to/page',
    meta: {
        charset: 'utf-8',
        name: {
            keywords: 'react,meta,document,html,tags'
        }
    }

and place a

<DocumentMeta {...meta} />

in the return

Solution 2 - Reactjs

You can use react-meta-tags. It allows you to write title and other meta tags in a declarative way and in normal jsx format, which will be moved to head (Check server usage on the doc).

import React from 'react';
import MetaTags from 'react-meta-tags';

class Component1 extends React.Component {
  render() {
    return (
        <div class="wrapper">
          <MetaTags>
            <title>Page 1</title>
            <meta id="meta-description" name="description" content="Some description." />
            <meta id="og-title" property="og:title" content="MyApp" />
            <meta id="og-image" property="og:image" content="path/to/image.jpg" />
          </MetaTags>
          <div class="content"> Some Content </div>
        </div>
      )
  }
}

You may also like to check react-helmet if you have an advanced use case.

Solution 3 - Reactjs

You almost definitely want to use:

React Helmet

In contrast to react-meta-tags it can nest <Helmet>s and so you can define your meta tags deep within your app - like <title>s that should override each other. And in contrast to react-document-meta you can define things using jsx (and nest things).

This seems to be the solution that the community almost exclusively uses - 600,000 weekly downloads vs the 6,000 given in other solutions. "Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple, and React beginner friendly." - and has support for server-side rendering.

Here's an example, adapted from the front page:

<Parent>
    I'm a parent
    <Helmet>
        <title>My Title</title>
        <meta name="description" content="Helmet application" />
    </Helmet>
 
    <Child>
        I'm a child
        <Helmet>
            <title>Nested Title</title>
            <meta name="description" content="Nested component" />
        </Helmet>
    </Child>
</Parent>

outputs:

<head>
    <title>Nested Title</title>
    <meta name="description" content="Nested component">
</head>
<Parent>
    I'm a parent
    <Child>
        I'm a child
    </Child>
</Parent>

Solution 4 - Reactjs

You cand also give the page title and meta tags description in the following way.

place a meta tag of description in your index.html file like this.

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Dynamic Page title here</title>

in your .js files or .jsx files below the render() method write the page title and meta description for the page like this .

render()
{
document.title ="Welcome | here is your page title to display"; 
document.getElementsByTagName("META")[2].content="Your description about the page or site here to set dynamically";

return(
	<div>Page content</div>
);
}

Solution 5 - Reactjs

Firstly if you don't need dynamic data you can just edit public/index.html.

For dynamic data the React team recommends to either use react-helmet

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

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>React app</title>
                <meta name="description" content="React application" />
            </Helmet>
            ...
        </div>
    );
  }
};

Or using placeholders and replacing them server-side:

<html lang="en">
  <head>
    <meta property="og:title" content="__OG_TITLE__" />
    <meta property="og:description" content="__OG_DESCRIPTION__" />
  </head>
</html>

Solution 6 - Reactjs

According to the official documentation React Doc - Title and Meta Tags, you can also use React Helmet

Solution 7 - Reactjs

You can use the document query and update their values.

const setTitle = title => {
    const el = document.querySelector('title');
    el.innerText = `${el.text} | ${title}`;
  };

const setDescription = desc => {
    const el = document.querySelector("meta[name='description']");
    el.setAttribute('content',desc)
  }

Solution 8 - Reactjs

As create-react-app docs mentioned:

> If you need to dynamically update the page title based on the content, you can use the browser document.title API. For more complex scenarios when you want to change the title from React components, you can use React Helmet, a third party library.

A simple example:

function App(){
  document.title = "Home";
  return (
   <div>...</div>
  )
}

Solution 9 - Reactjs

Maybe it's late but you can do this very simply like this:

Just use useEffect() in your component like:

useEffect(() => {
  document.head.innerHTML+=`
  <meta name='description' content='My description value!!!'/>
  <meta name='keywords' content='My keywords!!!'/>
  `
}, []);

Solution 10 - Reactjs

Not sure if this is the answer you were looking for but I was searching for how to update the info your react app shows when you preview the link in some other app. Every solution I tried wasn't working with github pages and react (react-helmet, react-meta-tags, react-document-meta). What ended up working was that you can edit the index.html located inside the public folder to change this info. Include this somewhere in the head:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/IMDB.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>IMDB</title>
    <meta property="og:audio" content="http://example.com/bond/theme.mp3" />
    <meta property="og:description" 
      content="Sean Connery found fame and fortune as the
               suave, sophisticated British agent, James Bond." />
    <meta property="og:determiner" content="the" />
    <meta property="og:locale" content="en_GB" />
    <meta property="og:locale:alternate" content="fr_FR" />
    <meta property="og:locale:alternate" content="es_ES" />
    <meta property="og:site_name" content="IMDb" />
    <meta property="og:video" content="http://example.com/bond/trailer.swf" />

Example from https://ogp.me/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarkirat SalujaView Question on Stackoverflow
Solution 1 - ReactjsKRONWALLEDView Answer on Stackoverflow
Solution 2 - ReactjsSudhanshu YadavView Answer on Stackoverflow
Solution 3 - ReactjseedrahView Answer on Stackoverflow
Solution 4 - ReactjsVenkatesh SomuView Answer on Stackoverflow
Solution 5 - ReactjsthisismydesignView Answer on Stackoverflow
Solution 6 - ReactjsLaurent KhoudjaView Answer on Stackoverflow
Solution 7 - ReactjsFahd AllebdiView Answer on Stackoverflow
Solution 8 - ReactjsMejanView Answer on Stackoverflow
Solution 9 - Reactjsitsmehemant7View Answer on Stackoverflow
Solution 10 - ReactjsNick MalekiView Answer on Stackoverflow