HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactCritical

How do you set the document title in React?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youthesetreacttitlehowdocument

Problem

I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title in the constructor and componentDidMount() - none of these solutions work.

Solution

For React 16.8+ you can use the Effect Hook in function components:

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    document.title = 'My Page Title';
  }, []);
}


To manage all valid head tags, including ``, in declarative way, you can use React Helmet component:

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

const TITLE = 'My Page Title';

class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        
          { TITLE }
        
        ...
      
    )
  }
}

Code Snippets

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    document.title = 'My Page Title';
  }, []);
}
import React from 'react';
import { Helmet } from 'react-helmet';

const TITLE = 'My Page Title';

class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        <Helmet>
          <title>{ TITLE }</title>
        </Helmet>
        ...
      </>
    )
  }
}

Context

Stack Overflow Q#46160461, score: 319

Revisions (0)

No revisions yet.