Source:  Twitter logo

I'm building a navigation bar with React. The Navigation bar has various navigation items. When one of the navigation items is clicked, the class 'active' has to be added to the clicked item (this part is easily achievable with a new state tracking if it's active).

However when the 'active' class is added to one of the navigation items, the active class has to be removed from any other navigation items currently having it. This is straightforward with jQuery, but I'm guessing thats not the React best practice. What's the ideal way to remove the 'active' class from the sibling navigation items?

I think that the best approach would be handle this in the container component. Menu items don't need to know about each other, but container can. So container can give to children onClick callbacks. And later in callbacks container can set its state by setState. In render function you just pass active property to your MenuItem.

// ES6, React 0.14
var MenuItem = ({onClick, text, active}) => (
    <button onClick={onClick} style={active? {color: 'red'} : null}>{text}</button>
);

// example of use: <MenuBar buttons={['cat', 'dog', 'penguin']}/>
class MenuBar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {activeIndex: 0};
    }
    handleItemClick(index) {
        this.setState({activeIndex: index});
    }
    render() {
        var activeIndex = this.state.activeIndex;
        return <div>
            {
                this.props.buttons.map(
                    (btn, i) => (
                        <MenuItem
                            active={activeIndex === i}
                            key={i}
                            onClick={this.handleItemClick.bind(this, i)}
                            text={btn} />
                    )
                )
            }
        </div>
    }
}
6 users liked answer #0dislike answer #06
hex13 profile pic
hex13

I've started learning React recently so I'm not an expert. But I just started building some tabs and you can see my example here.

What I did was make a conditional isActive state that changed on a click event. Then the class was changed like so:

className={this.props.isActive ? "active" : null}
2 users liked answer #1dislike answer #12
cocoa profile pic
cocoa

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).