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.
Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .
Whenever we click on the checkbox the handleOnChange handler function will be called which we use to set the value of isChecked state. const handleOnChange = () => { setIsChecked(! isChecked); }; So if the checkbox is checked, we're setting the isChecked value to false .
Using setState with React Checkbox onChange Toggle the text of a paragraph with the checkbox using the 'useState' hook. */ import React, {useState} from 'react'; function Checkbox() { const [checked, setChecked] = useState(false); const handleChange = () => { setChecked(! checked); }; return ( <div> <p> {checked ?
Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen. This time, this.state.date in the render() method will be different, and so the render output will include the updated time. React updates the DOM accordingly.
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
};
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With