I’m currently trying to make the button to change background color to let the visitor know which page they are currently on. Anyone know how to do that? I’ve only managed to make it change color upon clicking.
I’m using react router in reactJS and for example i have 2 buttons, home and about, if im on home, the button colour will be blue, while the about button colour will be orange, and same goes otherwise, if im on about page, then the button will be blue and the home button will be orange.
but currently i can only manage the change color on click
const [btnClass, setBtnClass] = useState('blue-color');
function toggleColor() {
if (btnClass === 'blue-color') {
setBtnClass('orange-color');
} else {
setBtnClass('blue-color');
}
}
return (
<div>
<nav className="nav">
<button
onClick={() => {
navigateHome();
toggleColor();
}}
className={`${btnClass} po-btn`}>Home</button>
<button
onClick={() => {
navigateToAbout();
toggleColor();
}}
className={`${btnClass} pr-btn`}>About</button>
<Routes>
<Route path="/about" element={<About />} />
<Route path="/" element={<Home />} />
</Routes>
</nav>
</div>
);
}
2
Answers
if I am guessing right you want to show highlighted color when a user is on the About page for example what you can do is change the route url when the user go to the About page and get the current route details in
useEffect
withwindow.location.pathname
to get the path and manipulate the colorI would suggest to use MUI framework for the menu buttons combined with Link from react-route-dom.
In useEffect you can check the location.pathname (through react-route-dom useLocation) and update the selectedIndex of the Tabs.
Then, in the CSS, the menu items will change background colors based on the selectedIndex.