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')
);
-
...is there a question here?Michael Parker– Michael Parker2016-08-05 19:13:03 +00:00Commented Aug 5, 2016 at 19:13
Add a comment
|
2 Answers
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
5 Comments
Egglabs
thank you, but my components are loading based on JSON render.
Egglabs
<button onClick={this.toggle}>toggle</button> <div className={'hide-' + this.state.hide}>{data.content}</div>
WitVault
In that case you can pass data as props to ToggleableComp or as children.
Egglabs
I have tried this jsfiddle.net/9lessons/t37Lk6p4/169 , could you please help me
WitVault
Please update the question in full detail what you want to achieve ? It will be easy to help.
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>;
}
});