DEV Community

artemismars
artemismars

Posted on

React - How to give a focus to a list item?

This topic is related to Menu on the website.

For example,
If you visit a website and click a menu item then you will move to other path showing different page.
But the menu item has a background color (focus).

I am going to show you how to implement that feature.

import {useLocation} from 'react-router-dom'
Enter fullscreen mode Exit fullscreen mode

We do this with react-router-dom library. It has a hook called useLocation.

const location = useLocation();

const styles = {
  active: {
    background: '#f4f4f4'
  }
}

return (
  <List>
    {menuItems.map(item => (
      <ListItem sx={location.pathname === item.path ? styles.active : null}>
        <ListItemIcon>{item.icon}</ListItemIcon>
        <ListItemText primary={item.text}/>
      </ListItem>
    ))}
  </List>
)
Enter fullscreen mode Exit fullscreen mode

important part

<ListItem sx={location.pathname === item.path ? styles.active : null}>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)