Kousha
Kousha

Reputation: 36219

Toggle class except if a child is clicked in React

I want to have a header where you can click it to hide/show it. But on this header, there will be a group of buttons that would be part of a child element. If you click these buttons, I don't want the whole thing collapse.

How can I achieve this in React? What I have so far is going to collapse everything, because Child is in Parent and under row

class Parent extends Component {
    constructor() {
        super();

        this.state = {
            show: false
        }
    }

    render() {
        return (
            <div className="row" onClick={() => this.setState({show: !this.state.show})}>
                <div className="col-2">
                    <Child/>
                </div>
                ...
            </div>
        )
    }
}

Upvotes: 1

Views: 66

Answers (2)

nrabinowitz
nrabinowitz

Reputation: 55678

You should be able to use stopPropagation() in the event handler for the buttons to prevent it from bubbling further. See http://facebook.github.io/react/docs/events.html for API details.

class Child extends Component {
    handleClick(event) {
        event.stopPropagation();
        doSomething();
    }

    render() {
        return (
            <button onClick={e => this.handleClick(e)}>
                Click Me!
            </button>
        );
    }
}

Upvotes: 1

gu mingfeng
gu mingfeng

Reputation: 1050

In Child's onClick event handler, add this line

event.stopPropagation()

Upvotes: 1

Related Questions