Home > other >  Can I change page title in reactjs in this way (using useState and useEffect)?
Can I change page title in reactjs in this way (using useState and useEffect)?

Time:02-19

I don't know why it's not working. Does it have any syntax error tho?

const [pageTitle, setPageTitle] = useState("My Financial Right Hand");
useEffect(() => {
    document.title = pageTitle;
}, [pageTitle]);
function changePageTitle(props) {
    setPageTitle(props);
};

and inside render:

{changePageTitle("Main Page")}

CodePudding user response:

You should use react-helmet which runs as a side effect to change the title, metadata ...etc.

import React, { useEffect, useState } from "react";
import { Helmet } from "react-helmet";

export default function App() {
  const [pageTitle, setPageTitle] = useState("My Financial Right Hand");

  return (
    <>
      <Helmet>
        <title>{pageTitle}</title>
      </Helmet>
      <p>tsample text</p>
    </>
  );
}

Edit brave-stitch-hnt31f

CodePudding user response:

Try implementing a custom hook

export function useTitle(title) {
 useEffect(() => {
    const prevTitle = document.title
    document.title = title
      return () => {
         document.title = prevTitle
      }
  })
}

call the function as below

const MyComponent = () => {
  useTitle("New Title")
 return (
   <div>
     ...
   </div>
 )
}
  • Related