Reputation: 3186
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/
Upvotes: 0
Views: 1216
Reputation: 3186
Solution for this question, try to click comment button.
var EachCom = React.createClass({
getInitialState: function(){
return { showComment: false };
},
commentLink: function()
{
this.setState({ showComment: !this.state.showComment });
this.renderCommentForm;
},
renderCommentForm: function()
{
if(this.state.showComment)
{
return (<CommentForm />)
}
},
render: function(){
return <div><br/>
<button onClick={this.commentLink}> comment </button>
{this.renderCommentForm()}
</div>
}
});
var TaskList = React.createClass({
render: function(){
return <div>
{this.props.items.map((task, taskIndex) =>
<div key={taskIndex}>
{task}
<EachCom />
</div>
)}
</div>;
}
});
http://jsfiddle.net/9lessons/t37Lk6p4/171/
Upvotes: 0
Reputation: 24130
You are using a common state variable to toggle the div
. Since it is shared among all div
s 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
Upvotes: 3