0

I'm trying to have a different navbar for each path in my website, i figured out a way but it doesn't really change until I refresh the page which is obviously not what i want. ( I'm using react router v6.3 )

    function Navbar() {
if (window.location.pathname === "/") {
return (
<nav style={{ backgroundColor: "rgb(17, 105, 142)" }}>...</nav>
);
} else if (window.location.pathname === "/products") {
return (
<nav className="products-nav">...</nav>
);
} else if (window.location.pathname === "/addproducts") {
return (
<nav className="addproducts-nav">...</nav>
);
} else ...

Here's the full code just in case

AlaaKudo810
  • 113
  • 9

2 Answers2

0

If you're using react router you shouldn't be using window.location directly anymore. Use the values available from react router. window.location changes won't trigger a re-render which is why you aren't seeing your changes.

The react router equivalent would be to use the useLocation hook

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
0

You can use useLocation hook from react-router-dom which returns the current location object https://reactrouter.com/en/main/hooks/use-location

import React from 'react'
import useLocatio from 'react-router-dom'

const functionalComponent = () => {
    const location = useLocation();
    console.log(location.pathname)
    return ...
}
Shakya Peiris
  • 504
  • 5
  • 11