by Sai gowtham

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.

App.js
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.

customHooks.js
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:

App.js
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.

App.js
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;

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course