Ads

React Js 11 - Using Hooks Set document title in React JS

Hello Friends,

I am Chakrapani Upadhyaya Full Stack Engineer, In this article you will learn about title tag and how to set up that in your react application.

What is Title?

title contains the title of the document which displays at the top of the browser window or is used as the Bookmark name when adding a web page to your Favorites. This tag is also commonly referred to as the <title> element.

Please find the screen shown below.

Lets assume your application has 3 pages 1. Home, 2. About Us and 3. Contact Us page

Home page should display Home : DashBoard, About Us should display About Us and finally Contact Us should display Contact Us

We can do this in HTML page just adding the title tag inside head part, shown below

<html>
     <head>
            <title>Home : Dashboard</title>
    </head>
    <body>
    
    </body>
</html>

 How about in React Application?

As React JS is single page application and totally depends on components, is it is complex to set the document title in React Js application 

Answer is Not at all, its really super easy

In functional component we can use Effect hook, to set the document title. This hook executes at the initial stage when the component is mounted and also when the components state changes or the component re-renders. 

Inside the useEffect hook, we can simply set the document title as shown in the code snippet below:

Note : I am not concentrating on class component

 

import React, { useEffect } from 'react'

function Home() {

    useEffect(()=>{
        document.title="Home : Dashboard"
    },[])

  return (
    <div>Home</div>
  )
}

export default Home


we can do same thing for other components(About Us and Contact Us)

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

I hope you enjoyed this article. 

That's it for right now, see you in next article until then take care bye bye 😄

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !