javascriptreactjsdom

How do you set the document title in React?


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 <title>, 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 (
          <>
            <Helmet>
              <title>{ TITLE }</title>
            </Helmet>
            ...
          </>
        )
      }
    }