U
U
uuushka2015-11-23 15:16:09
css
uuushka, 2015-11-23 15:16:09

How to make a vertical menu in React with a menu item highlighted?

Good afternoon. I'm new to react, so I'm hoping for your advice
. What I mean:
got an array, drew a menu on it

render() {
    return (
        <ul className="nav nav-pills nav-stacked ">
            {this.props.itemList.map(
                function (item) {
                    return <MenuItem item={item}  />
                }
            )}
        </ul>
    )
};

It is necessary that when you click on a menu item, it is highlighted in a different color. It all worked out. But how to make it so that when you click on another element, this selection is removed and appears on another element?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-11-23
@iNikNik

It is necessary that when you click on a menu item, it is highlighted in a different color. It all worked out.

It's weird that one works and the other doesn't. The mechanism is the same. The simplest implementation involves storing the selected menu item in the state:
class MyMenu extends React.Component {

  constructor(props) {
    super(props);
    this.handleItemClick = this.handleItemClick.bind(this);
    this.state = { selectedItem: null };
  }

  handleItemClick(selectedItem) {
    console.log('handleItemClick', selectedItem);
    this.setState({ selectedItem });
  }

  render() {
    const { items } = this.props;
    const { selectedItem } = this.state;
    const { handleItemClick } = this;

    return (
      <ul>
        { items.map( (item, key) => (
            <MenuItem
                key={key}
                item={item}
                isActive={item === selectedItem}
                onClick={handleItemClick}
             />
        )) }
      </ul>
    );
  }
}

And, accordingly, in the MenuItem component itself, we check - if the flag isActive === true, then we add a class or something else:
Working example

A
Alexey Zuev, 2015-11-23
@yurzui

jsfiddle.net/yurzui/1gfu213e/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question