How to highlight the after the user clicked?
<Box py={2}>
<Grid container width="330px">
<Grid container direction="column" item xs align="left">
<Grid item>
<Typography
variant="h6"
className="locationTitle"
display="block"
>
{' '}
{location.name}{' '}
</Typography>
</Grid>
</Grid>
</Grid>
<Typography variant="body" display="block">
{' '}
{location.address.street1}
</Typography>
</Box>
css
.css-1yjo05o:hover{
background-color: lightgray;
}
the hover is fine but when i tried to :focus
and :target
, it doesnt work
CodePudding user response:
You should never style the hashes generated by the Mui styling engine. They are not static. Instead, you want an onClick
listener that toggles a className
(if you are using CSS) or an SX prop (if you are using @mui/material).
const [highlight, setHighlight] = useState(false)
<Box
py={2}
onClick={() => setHighlight(!highlight)}
sx={{ bgcolor: highlight ? 'lightgrey' : 'unset' }}
>
Of course this has the potential to highlight more than 1 box at a time. If you want 1 box at a time, you have to lift the state up to the parent component and use the child's index to toggle the highlight. Demo.