Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: setState with checkbox: checked or unchecked

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.

like image 320
Sylar Avatar asked Oct 19 '15 07:10

Sylar


People also ask

How do you know checkbox is checked or not in Reactjs?

Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .

How does checkbox handle state of React?

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 .

How do you handle a checkbox change in React?

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 ?

What happens when setState is called React?

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.


1 Answers

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
        };
    }
});
like image 179
J3Y Avatar answered Nov 11 '22 09:11

J3Y