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…


This content originally appeared on DEV Community and was authored by artemismars

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'

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>
)

important part

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


This content originally appeared on DEV Community and was authored by artemismars


Print Share Comment Cite Upload Translate Updates
APA

artemismars | Sciencx (2022-03-24T14:16:50+00:00) React – How to give a focus to a list item?. Retrieved from https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/

MLA
" » React – How to give a focus to a list item?." artemismars | Sciencx - Thursday March 24, 2022, https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/
HARVARD
artemismars | Sciencx Thursday March 24, 2022 » React – How to give a focus to a list item?., viewed ,<https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/>
VANCOUVER
artemismars | Sciencx - » React – How to give a focus to a list item?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/
CHICAGO
" » React – How to give a focus to a list item?." artemismars | Sciencx - Accessed . https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/
IEEE
" » React – How to give a focus to a list item?." artemismars | Sciencx [Online]. Available: https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/. [Accessed: ]
rf:citation
» React – How to give a focus to a list item? | artemismars | Sciencx | https://www.scien.cx/2022/03/24/react-how-to-give-a-focus-to-a-list-item/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.