Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  83] [ 2]  / answers: 1 / hits: 21407  / 9 Years ago, mon, october 19, 2015, 12:00:00

I'm currently testing the waters with Reactjs. Based on their docs, I have whipped up a small project that I'm stuck with. So far, when the checkbox is checked, the state changes but....not sure how to change a state unchecked:



var Foo = React.createClass{(
getInitialState: function() {
return {
location: true,
}
},

onClick: function() {
this.setState({ location: false });
},

render: function() {

var inlineStyles = {
display: this.state.location ? 'block' : 'none'
};
return (
<div>
<input type=checkbox
onClick={this.onClick}
/> show / hide bar
<hr />
<div style={inlineStyles}>
<p>bar</p>
</div>
</div>
);
}

)};


Do I need to use an if statement for the sort of thing I want? I need to this.setState.location: true when unchecked.


More From » reactjs

 Answers
13

You need to read the state of the checkbox during a click, and apply that to your React state.


var Foo = React.createClass({
render: function() {
return <input type="checkbox" onClick={this.onClick} checked={!this.state.location}></input>
},

onClick: function(e) {
this.setState({location: !e.target.checked});
},

getInitialState: function() {
return {
location: true
};
}
});

[#64689] Friday, October 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sylviakaitlinj

Total Points: 564
Total Questions: 114
Total Answers: 105

Location: Jordan
Member since Thu, Aug 11, 2022
2 Years ago
sylviakaitlinj questions
;