How to dynamically change title in vite react.js?

by giovanny.lueilwitz , in category: Javascript , a month ago

How to dynamically change title in vite react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , a month ago

@giovanny.lueilwitz 

You can dynamically change the title of a React.js application built with Vite by using the useEffect hook to update the document title whenever a certain state or prop changes. Here's an example of how you can achieve this:

  1. Define a state variable to hold the title in your component:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { useState, useEffect } from 'react';

function App() {
  const [pageTitle, setPageTitle] = useState('Default Title');

  return (
    <div>
      <h1>{pageTitle}</h1>
    </div>
  );
}


  1. Use the useEffect hook to update the document title whenever the pageTitle state changes:
1
2
3
useEffect(() => {
  document.title = pageTitle;
}, [pageTitle]);


  1. Now you can update the title dynamically by calling setPageTitle with a new title whenever needed:
1
setPageTitle('New Page Title');


By following these steps, you can dynamically change the title of your React.js application built with Vite.