Egglabs Egglabs - 3 months ago 50
React JSX Question

How to toggle component based on click index in ReactJS

var Comp = React.createClass({
getInitialState: function(){
return {hide: false};
},
toggle: function(){
this.setState({hide: !this.state.hide});
},
render: function() {
return <div>
<button onClick={this.toggle}>toggle</button>
<div className={'hide-' + this.state.hide}>Hi there</div>

<button onClick={this.toggle}>toggle</button>
<div className={'hide-' + this.state.hide}>Hi there</div>

<button onClick={this.toggle}>toggle</button>
<div className={'hide-' + this.state.hide}>Hi there</div>

<button onClick={this.toggle}>toggle</button>
<div className={'hide-' + this.state.hide}>Hi there</div>
</div>;
}
});

ReactDOM.render(
<Comp />,
document.getElementById('container')
);


https://jsfiddle.net/9lessons/aLd1w6qs/3/

Answer

You are using a common state variable to toggle the div. Since it is shared among all divs changing visibility of one would change all of them simultaneously.

You can create either separete state variable for each of div e.g hide1, hide2 .....hideN.

Or

Try another approach- creating separate component itself.

var ToggleableComp = React.createClass({
    getInitialState:function() {
        return {hide: false};
    },
    toggle: function(){
        this.setState({hide: !this.state.hide});
    },
    render: function() {
      return (
        <div>
        <button onClick={this.toggle}>toggle</button>    
            <div className={'hide-' + this.state.hide}>{this.props.children}</div>
        </div>
      );
    }
});

var Comp = React.createClass({
    render: function() {
        return (
           <div>
             <ToggleableComp>Json Data 1</ToggleableComp>
             <ToggleableComp>Json Data 2</ToggleableComp>
             <ToggleableComp>Json Data 3</ToggleableComp>
             <ToggleableComp>Json Data 5</ToggleableComp>
        </div>
      );
    }
});

ReactDOM.render(
    <Comp />,
    document.getElementById('container')
);

Check this fiddle

Comments