Reputation:
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")}
Upvotes: 1
Views: 767
Reputation: 1159
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>
)
}
Upvotes: 2
Reputation: 13265
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>
</>
);
}
Upvotes: 3