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>
</>
);
}
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>
)
}