How to update meta tags in React.js?
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?
Solution 1:
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:
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.