How to change document title in React




When you create a react app using the create-react-app command, it will give us a boilerplate code. When you run the code, we can see the title will be always React App

<img src="https://static.onecompiler.com/images/posts/3w3t4tcjw/reactapp.png" />

So, in this post let's see how can we change that.

Method 1

This method is useful if you want the title to be changed to all routes.
Go to index.html in your public folder and change the <title> tag.

<img src="https://static.onecompiler.com/images/posts/3w3t4tcjw/index.png" />

This method works great! but the problem is you will have a fixed title for every route. If you want your route title to be dynamic follow the method 2

Method 2

This method is great if you need your title to be page specific.
Go the component you want to change the title and in the useEffect hook add as shown below at the end

useEffect (() => {
	document.title ="page name";
}, [])
<img src="https://static.onecompiler.com/images/posts/3w3t4tcjw/title.png" />