Home > Net >  Update a value in react based on the url pathname change
Update a value in react based on the url pathname change

Time:01-26

So here is the situation. I have a Navbar component, which has a title, and I have a few routes with different pathnames, let's say /path1, /path2, and /path3. What I want to achieve, is that every route I visit, I expect to see a different title for App bar.

In my appbar component, I tried this:

const [appBarTitle, setAppBarTitle] = useState('');

>     function listenToPopstate() {
>       if(window.location.pathname === '/path1') {
>       setAppBarTitle('/path1')
>     } else if(window.location.pathname === '/path2') {
>       setAppBarTitle('/path2')
>     }}

Then, I am using this function

> useEffect(() => {   window.addEventListener('popstate',
> listenToPopstate);   listenToPopstate();   return () =>
> window.removeEventListener('popstate', listenToPopstate); }, [])

And then I am passing the value to AppBar component as a title.

Expected behavior: Update app bar title after every reroute. Actual behavior: it does only after I refresh the page.

I was trying to understand, is there anything like onhashchange, for pathname change. So I don't know how to proceed.

Would appreciate any help or suggestion.

CodePudding user response:

I would probably take advantage of the useLocation hook from react-router-dom.

Here's a link to an example of what you're looking for.

Basically what you can do is use the pathname key from useLocation hook to determine what route you're on. And using the pathname as a key from the PAGE_TITLES object, return the updated title from that.

import { Link, useLocation } from "react-router-dom";

const PAGE_TITLES = {
  "/": "This is the Home page",
  "/child": "Welcome to the Child page"
};

function NavBar() {
  const { pathname } = useLocation();
  return (
    <ul>
      <h1>Page: {PAGE_TITLES[pathname]}</h1>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/child">Child</Link>
      </li>
    </ul>
  );
}
  •  Tags:  
  • Related