How to set a document title in React
In this tutorial, we will learn about how to set a document title from a react class components and hooks.
Setting document title using react hooks
In this example, we are using the react useEffect() hook to set a new document title from a functional component.
import React, { useEffect} from "react";
export default function App() {
useEffect(() => {
document.title = "Home Page"; }, []);
return (
<div className="App">
<h1>Hello React</h1>
</div>
);
}
Creating useDocTitle custom hook
Instead of using the same logic to set a document title on all components in our react app, let’s create a new custom hook called useDocTitle()
which helps us to reuse the logic between components.
import React, { useEffect, useState } from "react";
const useDocTitle = title => {
const [doctitle, setDocTitle] = useState(title);
useEffect(() => {
document.title = doctitle; }, [doctitle]);
return [doctitle, setDocTitle];
};
export {useDocTitle};
Usage:
import React from "react";
import {useDocTitle} from "customHooks"
export default function App() {
const [doctitle, setDocTitle] = useDocTitle("Home page");
return (
<div className="App">
<h1>Hello React</h1>
{/* changing title dynamically */}
<button onClick={() => setDocTitle("Home lab")}> Change title </button> </div>
);
}
Setting document title in class components
In class components, we can use the componentDidMount()
lifecycle method to set a document title.
import React from "react";
class App extends React.Component {
componentDidMount() {
document.title = "Home Page"; }
render() {
return (
<div className="App">
<h1>Hello React</h1>
</div>
);
}
}
export default App;