reactjsreact-routerreact-router-dompage-title

react router (react-router-dom) setting page title from current route (functional components)?


I thought this would be easy, but still can't find an easy solution. I simply want to set the page title (and document.title) to a specified string that I choose. I know I can access useLocation and get the current route, but that doesn't work with logical human naming. For example, my route might be /new but I want the title of the page to be 'Add New Thing'. Notice that I've added a new prop for the page title that seems like a logical place to add it (then use a useEffect to pull it), but can't figure out how to access this prop.

If this isn't the correct way, how would you do this? Should I instead setup a dictionary/lookup for the current url(useLocation) and assign a human page title?

Main goal: If someone DIRECTLY hits a URL '/new' how would you set the title?

My current structure is from a base create react app.

In my index.js

ReactDOM.render(
    <React.StrictMode>
      <Router>
        <App />
      </Router>
    </React.StrictMode>,
    document.getElementById('root')
);

app.js

<div className="quiz-app-row">
        <SideBarNav />
        <div className='quiz-app-col'>
          <h1>{TITLE HEREEEEE}</h1>
          <Switch>
            <Route exact component={Home} path="/" title='home' />
            <Route exact component={Example} path="/manage" title='example' />
            <Route exact component={CreateQuiz} path="/new" title='New Quiz' />
          </Switch>
        </div>
      </div>

Solution

  • Thanks all for the responses, but I feel most of them seem to be overkill for what I'm trying to accomplish, and no extra package needed. Instead, I just created a lookup collection and assigned the title that way. I will only have ~7 links total, so this seems manageable.

    const [pageTitle, setPageTitle] = useState('Home');
    
      const titleMap = [
        {path: '/', title:'Home'},
        {path: '/manage', title:'Manage'},
        {path: '/new', title:'New Quiz'}
      ]
    
      let curLoc = useLocation();
      useEffect(() => {
        const curTitle = titleMap.find(item => item.path === curLoc.pathname)
        if(curTitle && curTitle.title){
          setPageTitle(curTitle.title)
          document.title = curTitle.title
        }
      }, [curLoc])