Changing the document title in React?

Inside your componentDidMount() function in App.js (or wherever), simply have:

componentDidMount() {
    document.title = "Amazing Page";
}

The reason this works is anywhere in your react project you have access to the Js global scope. Go ahead and type window in your sites console. Basically everything there you will be able to access in your React project.


I now use react-helmet for this purpose, as it allows to customize different meta tags and links, and it also supports SSR.

import { Helmet } from 'react-helmet'

const Total = () => (
  <div className="text-center">
    <Helmet>
      <meta charSet="utf-8" />
      <title>{this.props.total}</title>
    </Helmet>
    <h1>{this.props.total}</h1>
  </div>
)

Original answer: there's actually a package by gaeron for this purpose, but in a declarative way:

import React, { Component } from 'react'
import DocumentTitle from 'react-document-title'

export default class Total extends Component {

  render () {
    return (
      <DocumentTitle title={this.props.total}>
        <div className='text-center'>
          <h1>{this.props.total}</h1>
        </div>
      </DocumentTitle>
    )
  }

}

Tags:

Dom

Reactjs