1.2 KiB
1.2 KiB
title, type, tags, author, cover, dateModified
| title | type | tags | author | cover | dateModified | ||
|---|---|---|---|---|---|---|---|
| React useTitle hook | snippet |
|
chalarangelo | blue-lake | 2021-09-27T05:00:00-04:00 |
Sets the title of the page
- Use
typeofto determine if theDocumentis defined or not. - Use the
useRef()hook to store the original title of theDocument, if defined. - Use the
useEffect()hook to setDocument.titleto the passed value when the component mounts and clean up when unmounting.
const useTitle = title => {
const documentDefined = typeof document !== 'undefined';
const originalTitle = React.useRef(documentDefined ? document.title : null);
React.useEffect(() => {
if (!documentDefined) return;
if (document.title !== title) document.title = title;
return () => {
document.title = originalTitle.current;
};
}, []);
};
const Alert = () => {
useTitle('Alert');
return <p>Alert! Title has changed</p>;
};
const MyApp = () => {
const [alertOpen, setAlertOpen] = React.useState(false);
return (
<>
<button onClick={() => setAlertOpen(!alertOpen)}>Toggle alert</button>
{alertOpen && <Alert />}
</>
);
};
ReactDOM.createRoot(document.getElementById('root')).render(
<MyApp />
);