How to set a document title in React

0
41

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>
        
      <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;

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here