javascriptreactjsreact-routerpage-title

Setting Page Title with React-Router-Config


I would like to set the page titles via the config file that I'm using with react-router-config but I'm not sure the best approach. Props? Helmet?

routes.js

const routes = [
    {
        title: 'Home',
        path: '/',
        exact: true,
        component: PageOne,
        name: PageOne,
    },
    {
        title: 'PageOne',
        path: '/PageOne',
        exact: true,
        component: PageOne,
        name: PageOne,
    }
]

template.js

const Template = ({ route }) => {
    return (
        <>
            <Nav route={route} />
        </>
    )
}

nav.js

const Nav = () => {
    return (
        <div>
             <Link to="/">Home</Link>
             <Link to="/PageOne">Page One</Link>
        </div>
    )
}

index.js

ReactDOM.render(
        <BrowserRouter>{renderRoutes(routes)}</BrowserRouter>,
    document.getElementById('root')
)

Solution

  • If you are using client side routing and react-hooks, you can simply write a custom hook that sets document title

    const useDocumentTitle = (title) => {
        useEffect(() => {
           document.title = title
        }, [ title])
    }
    

    and use it within each or your component

    const PageOne = ({ title }) => {
        useDocumentTitle(title);
        return (
            <>
                {/* Your content here */}
            </>
        )
    }