[reactjs] How to set default Checked in checkbox ReactJS?

I'm having trouble to update the checkbox state after it's assigned with default value checked="checked" in React.

var rCheck = React.createElement('input',
    {
        type: 'checkbox',
        checked: 'checked',
        value: true
    }, 'Check here');

After assigning checked="checked", I cannot interact the checkbox state by clicking to uncheck/check.

This question is related to reactjs checkbox

The answer is


<div className="display__lbl_input">
              <input
                type="checkbox"
                onChange={this.handleChangeFilGasoil}
                value="Filter Gasoil"
                name="Filter Gasoil"
                id=""
              />
              <label htmlFor="">Filter Gasoil</label>
            </div>

handleChangeFilGasoil = (e) => {
    if(e.target.checked){
        this.setState({
            checkedBoxFG:e.target.value
        })
        console.log(this.state.checkedBoxFG)
    }
    else{
     this.setState({
        checkedBoxFG : ''
     })
     console.log(this.state.checkedBoxFG)
    }
  };

There are a few ways to accomplish this, here's a few:

Written using State Hooks:

function Checkbox() {
  const [checked, setChecked] = React.useState(true);

  return (
    <label>
      <input type="checkbox"
        defaultChecked={checked}
        onChange={() => setChecked(!checked)}
      />
      Check Me!
    </label>
  );
}

ReactDOM.render(
  <Checkbox />,
  document.getElementById('checkbox'),
);

Here is a live demo on JSBin.

Written using Components:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isChecked: true,
    };
  }
  toggleChange = () => {
    this.setState({
      isChecked: !this.state.isChecked,
    });
  }
  render() {
    return (
      <label>
        <input type="checkbox"
          defaultChecked={this.state.isChecked}
          onChange={this.toggleChange}
        />
        Check Me!
      </label>
    );
  }
}

ReactDOM.render(
  <Checkbox />,
  document.getElementById('checkbox'),
);

Here is a live demo on JSBin.


I set the state as any[] type. and in the constructor set the state to null.

onServiceChange = (e) => {
    const {value} = e.target;
    const index = this.state.services.indexOf(value);
    const services = this.state.services.filter(item => item !== value);
    this.setState(prevState => ({
        services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
    }))
}

In the input element

this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/>

I figured it out after some time. Thought it might help y'all :)


You may pass "true" or "" to the checked property of input checkbox. The empty quotes ("") will be understood as false and the item will be unchecked.

let checked = variable === value ? "true" : "";
<input
     className="form-check-input"
    type="checkbox"
    value={variable}
    id={variable}
    name={variable}
    checked={checked}
/>
<label className="form-check-label">{variable}</label>

Don't make it too hard. First, understand a simple example given below. It will be clear to you. In this case, just after pressing the checkbox, we will grab the value from the state(initially it's false), change it to other value(initially it's true) & set the state accordingly. If the checkbox is pressed for the second time, it will do the same process again. Grabbing the value (now it's true), change it(to false) & then set the state accordingly(now it's false again. The code is shared below.

Part 1

state = {
  verified: false
} // The verified state is now false

Part 2

verifiedChange = e => {
  // e.preventDefault(); It's not needed
  const { verified } = e.target;
  this.setState({
    verified: !this.state.verified // It will make the default state value(false) at Part 1 to true 
  });
}; 

Part 3

  <form> 
      <input
          type="checkbox"
          name="verified"
          id="verified"
          onChange={this.verifiedChange} // Triggers the function in the Part 2
          value={this.state.verified}
      />
      <label for="verified">
      <small>Verified</small>
      </label>
  </form>

In my case I felt that "defaultChecked" was not working properly with states/conditions. So I used "checked" with "onChange" for toggling the state.

Eg.

checked={this.state.enabled} onChange={this.setState({enabled : !this.state.enabled})}

Here's a code I did some time ago, it might be useful. you have to play with this line => this.state = { checked: false, checked2: true};

class Componente extends React.Component {
  constructor(props) {
    super(props);

    this.state = { checked: false, checked2: true};
    this.handleChange = this.handleChange.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);

  }  

  handleChange() {
    this.setState({
        checked: !this.state.checked      
    })
  }

  handleChange2() {
    this.setState({
        checked2: !this.state.checked2      
    })
  }

  render() {
    const togglecheck1 = this.state.checked ? 'hidden-check1' : '';
    const togglecheck2 = this.state.checked2 ? 'hidden-check2' : '';

    return <div>
        <div>
        <label>Check 1</label>
        <input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
        <label>Check 2</label>
        <input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked2 } onChange={ this.handleChange2 } />
      </div>

      <div className={ togglecheck1 }>show hide div with check 1</div>
      <div className={ togglecheck2 }>show hide div with check 2</div>

    </div>;
  }
}

ReactDOM.render(
  <Componente />,
  document.getElementById('container')
);

CSS

.hidden-check1 {
  display: none;  
  }

.hidden-check2 {
  visibility: hidden;
}

HTML

  <div id="container">
      <!-- This element's contents will be replaced with your component. -->
  </div>

here's the codepen => http://codepen.io/parlop/pen/EKmaWM


in addition to the correct answer you can just do :P

<input name="remember" type="checkbox" defaultChecked/>

I tried to accomplish this using Class component: you can view the message for the same

.....

class Checkbox extends React.Component{
constructor(props){
    super(props)
    this.state={
        checked:true
    }
    this.handleCheck=this.handleCheck.bind(this)
}

handleCheck(){
    this.setState({
        checked:!this.state.checked
    })
}

render(){
    var msg=" "
    if(this.state.checked){
        msg="checked!"
    }else{
        msg="not checked!"
    }
    return(
        <div>
            <input type="checkbox" 
            onChange={this.handleCheck}
            defaultChecked={this.state.checked}
            />
            <p>this box is {msg}</p>
        </div>
    )
}

}


If someone wants to handle dynamic data with multiple rows, this is for handing dynamic data.

You can check if the rowId is equal to 0.

If it is equal to 0, then you can set the state of the boolean value as true.

interface MyCellRendererState {
    value: boolean;
}
constructor(props) {
        super(props);
        this.state = {
            value: props.value ? props.value : false
        };
        this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
    }
handleCheckboxChange() {
        this.setState({ value: !this.state.value });
    };
render() {
        const { value } = this.state;
        const rowId = this.props.rowIndex
        if (rowId === 0) {
           this.state = {
             value : true }
        }
        return ( 
          <div onChange={this.handleCheckboxChange}>
            <input 
            type="radio" 
            checked={this.state.value}
            name="print"
            /> 
          </div>
         )
      }

this can be done with pure js

              <Form.Group controlId="categoryStatus">
                <Form.Check
                  type="checkbox"
                  label="Category Status Active/In-active"
                  onChange={this.handleChecked}                 
                />
              </Form.Group>

  //Load category to form : to edit
  GetCategoryById(id) {
    this.UpdateId = id
    axios.get('http://localhost:4000/Category/edit/' + id)
      .then(response => {
        this.setState({
          category_name: response.data.category_name,
          category_description: response.data.category_description,
          is_active: response.data.is_active,
        });

        response.data.is_active == 1 ? document.getElementById("categoryStatus").checked = true : document.getElementById("categoryStatus").checked = false;
      })
      .catch(function (error) {
        console.log(error);
      })
  }



It`s working

<input type="checkbox" value={props.key} defaultChecked={props.checked} ref={props.key} onChange={this.checkboxHandler} />

And function init it

{this.viewCheckbox({ key: 'yourKey', text: 'yourText', checked: this.state.yourKey })}

 <div className="form-group">
          <div className="checkbox">
            <label><input type="checkbox" value="" onChange={this.handleInputChange.bind(this)}  />Flagged</label>
            <br />
            <label><input type="checkbox" value=""  />Un Flagged</label>
          </div>
        </div

handleInputChange(event){

console.log("event",event.target.checked)   }

the Above handle give you the value of true or false upon checked or unChecked


In the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you often want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue or defaultChecked attribute instead of value.

        <input
          type="checkbox"
          defaultChecked={true}
        />

Or

React.createElement('input',{type: 'checkbox', defaultChecked: true});

Please checkout more details regarding defaultChecked for checkbox below: https://reactjs.org/docs/uncontrolled-components.html#default-values


To interact with the box you need to update the state for the checkbox once you change it. And to have a default setting you can use defaultChecked.

An example:

<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />