How do you set the document title in React?

JavascriptReactjsDom

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

import React from 'react'
import ReactDOM from 'react-dom'


class Doc extends React.Component{
  componentDidMount(){
  	document.title = "dfsdfsdfsd"
  }
  
  render(){
  	return(
      <b> test </b>
    )
  }
}

ReactDOM.render(
  <Doc />,
  document.getElementById('container')
);

This works for me.

Edit: If you're using webpack-dev-server set inline to true

Solution 2 - Javascript

You can use React Helmet:

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>
        ...
      </>
    )
  }
}

Solution 3 - Javascript

For React 16.8, you can do this with a functional component using useEffect.

For Example:

useEffect(() => {
   document.title = "new title"
}, []);

Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.

Solution 4 - Javascript

As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.

If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.

You can edit this directly or use a placeholder which will be filled from environmental variables:

/.env:

REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...

If for some reason I wanted a different title in my development environment -

/.env.development:

REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...

/public/index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
         ...
         <title>%REACT_APP_SITE_TITLE%</title>
         ...
     </head>
     <body>
         ...
     </body>
</html>

This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:

console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!

See: Adding Custom Environment Variables

Solution 5 - Javascript

Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

this can be used in any react component, e.g.:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.

Solution 6 - Javascript

import React from 'react';

function useTitle(title: string): void => {
  React.useEffect(() => {
    const prevTitle = document.title;
    document.title = title;

    return () => {
      document.title = prevTitle;
    };
  }, []);
}

function MyComponent(): JSX.Element => {
  useTitle('Title while MyComponent is mounted');

  return <div>My Component</div>;
}

This is a pretty straight forward solution, useTitle sets the document title and when the component unmounts it's reset to whatever it was previously.

Solution 7 - Javascript

React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:

Here's an example:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
	constructor(props) {
		super(props);
		this.titleEl = document.getElementsByTagName("title")[0];
	}
	
	render() {
		let fullTitle;
		if(this.props.pageTitle) {
			fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
		} else {
			fullTitle = this.props.siteTitle;
		}
		
		return ReactDOM.createPortal(
			fullTitle || "",
			this.titleEl
		);
	}
}
Title.defaultProps = {
	pageTitle: null,
	siteTitle: "Your Site Name Here",
};

export default Title;

Just put the component in the page and set pageTitle:

<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

Solution 8 - Javascript

If you are wondering, you can set it directly inside the render function:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    render() {
        document.title = 'wow'
        return <p>Hello</p>
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

For function component:

function App() {
    document.title = 'wow'
    return <p>Hello</p>
}

But, this is a bad practice as stated by Elias in the comment.

The good practice:

Class component:

class App extends React.Component {
    // you can also use componentDidUpdate() if the title is not static
    componentDidMount(){
        document.title = "good"
    }

    render() {
        return <p>Hello</p>
    }
}

Function component:

function App() {
    // for static title, pass an empty array as the second argument
    // for dynamic title, put the dynamic values inside the array
    // see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
    useEffect(() => {
        document.title = 'good'
    }, []);

    return <p>Hello</p>
}

Solution 9 - Javascript

you should set document title in the life cycle of 'componentWillMount':

componentWillMount() {
    document.title = 'your title name'
  },

Solution 10 - Javascript

Simply you can create a function in a js file and export it for usages in components

like below:

export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}

and use it in any component like this:

import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end

class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }

  render() {
    return (
      <div>
        see the title
      </div>
    );
  }
}

export default App

Solution 11 - Javascript

You have multiple options for this problem I would highly recommend to either use React Helmet or create a hook using useEffect. Instead of writing your own hook, you could also use the one from react-use:

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

const MyComponent => () => (
  <Helmet>
    <title>My Title</title>
  </Helmet>
)
react-use
import React from 'react';
import { useTitle } from 'react-use';

const MyComponent = () => {
  useTitle('My Title');

  return null;
}

Solution 12 - Javascript

You can use the following below with document.title = 'Home Page'

import React from 'react'
import { Component } from 'react-dom'


class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }

  render(){
    return(
      <p> Title is now equal to Home Page </p>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

or You can use this npm package npm i react-document-title

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


class App extends Component{
  

  render(){
    return(
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Happy Coding!!!

Solution 13 - Javascript

Helmet is really a great way of doing it, but for apps that only need to change the title, this is what I use: (modern way React solution - using Hooks)

  1. Create change page title component
import React, { useEffect } from "react";

const ChangePageTitle = ({ pageTitle }) => {
  useEffect(() => {
    const prevTitle = document.title;
    document.title = pageTitle;
    return () => {
      document.title = prevTitle;
    };
  });

  return <></>;
};

export default ChangePageTitle;
  1. Use the component
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";

...

return (
    <>
      <ChangePageTitle pageTitle="theTitleYouWant" />
      ...
    </>
  );

...

Solution 14 - Javascript

I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.

interface Props {
    children: string|number|Array<string|number>,
}

export default class DocumentTitle extends React.Component<Props> {

    private oldTitle: string = document.title;

    componentWillUnmount(): void {
        document.title = this.oldTitle;
    }

    render() {
        document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
        return null;
    }
}

Usage:

export default class App extends React.Component<Props, State> {

    render() {
        return <>
            <DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
            <Container>
                Lorem ipsum
            </Container>
        </>
    }
}

Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.

By updating the document.title inside render() it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.

Solution 15 - Javascript

You can use ReactDOM and altering <title> tag

ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);

Solution 16 - Javascript

the easiest way is to use react-document-configuration

npm install react-document-configuration --save

Example:

import React from "react";
import Head from "react-document-configuration";

export default function Application() {
    return (
        <div>
            <Head title="HOME" icon="link_of_icon" />
            <div>
                <h4>Hello Developers!</h4>
            </div>
        </div>
    );
};```

Solution 17 - Javascript

const [name, setName] = useState("Jan");
  useEffect(() => 
    {document.title =   "Celebrate " +  {name}.name  ;}
  );
  

Solution 18 - Javascript

I wanted to use page title to my FAQ page. So I used react-helmet for this.

First i installed react-helmet using npm i react-helmet

Then i added tag inside my return like this:

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

const PAGE_TITLE = 'FAQ page'

export default class FAQ extends Component {
render () {
return (
<> { PAGE_TITLE }

This is my faq page

) } }

Solution 19 - Javascript

If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.

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
QuestioneliView Question on Stackoverflow
Solution 1 - JavascriptAlexVestinView Answer on Stackoverflow
Solution 2 - JavascriptquotesBroView Answer on Stackoverflow
Solution 3 - JavascriptJordan DanielsView Answer on Stackoverflow
Solution 4 - JavascriptGruffyView Answer on Stackoverflow
Solution 5 - JavascriptMaster BruceView Answer on Stackoverflow
Solution 6 - JavascriptShortchangeView Answer on Stackoverflow
Solution 7 - JavascriptColonel Thirty TwoView Answer on Stackoverflow
Solution 8 - JavascriptM Imam PratamaView Answer on Stackoverflow
Solution 9 - JavascriptAlvinView Answer on Stackoverflow
Solution 10 - Javascriptamin mshView Answer on Stackoverflow
Solution 11 - JavascriptmarcobiedermannView Answer on Stackoverflow
Solution 12 - JavascriptaccimeesterlinView Answer on Stackoverflow
Solution 13 - JavascriptAleksandar HristovView Answer on Stackoverflow
Solution 14 - JavascriptmpenView Answer on Stackoverflow
Solution 15 - Javascriptreza moradiView Answer on Stackoverflow
Solution 16 - Javascriptuser11290595View Answer on Stackoverflow
Solution 17 - JavascriptSai GarudaView Answer on Stackoverflow
Solution 18 - JavascriptANOOP NAYAKView Answer on Stackoverflow
Solution 19 - JavascriptStanflowsView Answer on Stackoverflow