Reputation: 255
I want to show the selected item highlighted in my drawer. Following is my code
<Link to ="/#" style={{textDecoration:'none'}}>
<ListItem button selected={selectedIndex === 0} onClick={(event) => handleListItemClick(event, 0)} >
<ListItemIcon>
<HomeIcon color="secondary"/>
</ListItemIcon>
<ListItemText primary="Home" />
</ListItem>
</Link>
<Link to ="/movies" style={{textDecoration:'none'}}>
<ListItem button selected={selectedIndex === 1} onClick={(event) => handleListItemClick(event, 1)}>
<ListItemIcon>
<MovieFilterIcon />
</ListItemIcon>
<ListItemText primary="Movies" />
</ListItem>
</Link>
following are the functions I call for the drawer
const [selectedIndex, setSelectedIndex] = React.useState(1);
const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
What I want is when I click on the movies it should go to movies & movies list item should show as active. I am open to suggestions
Upvotes: 0
Views: 1373
Reputation: 212
The issue you're likely facing is selectedIndex
resetting to its default state (in your case, 1) when the new page is navigated to.
The simplest fix is to add a useEffect function to set the correct value for selectedIndex
when the client mounts. Switch over the browser's URL to determine which value to set:
useEffect(() => {
switch (window.location.pathname) {
case "/":
setSelectedIndex(0)
break
case "/movies":
setSelectedIndex(1)
break
default:
break
}
}, [])
Here's a CodeSandbox with a setup similar to yours so you can see everything in detail
Upvotes: 2