Using React Router and Material UI, I'm trying to set the navigation item selected state based on the current URL path. If a user comes to a specific page, it should set the selected state of the appropriate link in the sidebar.
This is the current setup, but not sure what property I'm missing to set the active state based on the URL path using React Router
data.navigation
"navigation":[
{
"label":"Introduction",
"path": "/"
},
{
"label":"Page Two",
"path": "pagetwo"
}
]
import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom';
const [selectedIndex, setSelectedIndex] = useState(0);
const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
{data && data.navigation.map((item, i) =>
<Link key={i} to={`${item.path}`} className={classes.link}>
<ListItem button selected={selectedIndex === i} onClick={(event) => handleListItemClick(event, i)}>
<ListItemText className={classes.navLink}>{item.label}</ListItemText>
</ListItem>
</Link>
)}