I would like to setup a master/detail view and have a List
on the left, Drawer
on the right.
How can I have the last selected ListItem
stay highlighted?
I'm using material-ui@next.
Another solution is to leverage window.location.pathname
<ListItemButton
selected={window.location.pathname==="/path/to/current/page"}
component="a" href="/path/to/current/page>
</ListItemButton>
You should use MenuItem
instead of ListItem
. As described in the docs:
The
MenuItem
is a wrapper aroundListItem
with some additional styles.
One of those additional styles is the selected
option, which you can set using the selected
prop:
<MenuItem button selected>
<ListItemIcon>
<FolderIcon />
</ListItemIcon>
<ListItemText primary="Archives" />
</MenuItem>
Here's a rough proof of concept that uses state
to track and update the most recently clicked item:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import List, { ListItemIcon, ListItemText } from 'material-ui/List';
import { MenuItem } from 'material-ui/Menu';
import InboxIcon from 'material-ui-icons/Inbox';
import DraftsIcon from 'material-ui-icons/Drafts';
import FolderIcon from 'material-ui-icons/Folder';
const styles = theme => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
});
class SimpleList extends React.Component {
constructor(props) {
super(props);
this.state = { selected: null };
}
updateSelected(selectedIndex) {
this.setState({ selected: selectedIndex });
}
render() {
const { classes } = this.props;
const { selected } = this.state;
return (
<div className={classes.root}>
<List>
<MenuItem button onClick={() => this.updateSelected(0)} selected={selected === 0}>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</MenuItem>
<MenuItem button onClick={() => this.updateSelected(1)} selected={selected === 1}>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</MenuItem>
<MenuItem button onClick={() => this.updateSelected(2)} selected={selected === 2}>
<ListItemIcon>
<FolderIcon />
</ListItemIcon>
<ListItemText primary="Archives" />
</MenuItem>
</List>
</div>
);
}
}
SimpleList.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleList);
In MUI v5, you can use ListItemButton
and use the selected
prop to highlight the current list item:
const [selectedIndex, setSelectedIndex] = React.useState(1);
const buttonProps = (value) => ({
selected: selectedIndex === value,
onClick: () => setSelectedIndex(value),
});
<List>
<ListItemButton {...buttonProps(0)}>
<Content1 />
</ListItemButton>
<ListItemButton {...buttonProps(1)}>
<Content2 />
</ListItemButton>
<ListItemButton {...buttonProps(2)}>
<Content3 />
</ListItemButton>
</List>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With