A react hook to manage html page titles using react route
In this tutorial, we will create a hook for managing page titles in a react application.To understand what the html page titles are you can read this : w3Schools . The article states the following the reasons why we need to set page titles.
Whilst there are different existing solutions for managing page titles, I find using this method gives you a lot of flexibility. This tutorial assumes some knowledge of React.js and node.js We will use create react app and running on node version 16.
For out set up. First run the command below:
yarn create react-app page-titles-app
When this is done, we start the application by running yarn start.
cd page-titles-app
yarn start
Starts the development server.
Next, Let is install router router version 6
yarn add react-router-dom@6
Lets create some small components for testing
function SportsPage() {
return (
<div>
<h1> Sports Page </h1>
</div>
);
}
NewsPage, EntertainmentPage etc ..
// usePageTitle.js
import {
useMatch,
useLocation
} from "react-router-dom";
export default function usePageTitle() {
const location = useLocation();
const match = useMatch(location.pathname);
switch (true) {
case match?.pathname === "/sports": {
document.title = "Sports page";
break;
}
case match?.pathname === "/news": {
document.title = "General News";
break;
}
case match?.pathname === "/entertainment": {
document.title = "Entertainment Page";
break;
}
default: {
document.title = "My app page title";
}
}
}
Now just run the hook in every page where you need it.
function SportsPage() {
usePageTitle();
return (
<div><h1>Sports Page</h1></div> );
}
Useful links used in this tutorial:
Created by
I am a Software / UI developer with interests in Search Intensive applications, Information Architectures(IA), UX/UI, FRP, and Reusable Frontend Components Design.