266

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.

Rich
  • 3,928
  • 4
  • 37
  • 66
Yarin Nim
  • 3,607
  • 3
  • 14
  • 15
  • 7
    https://facebook.github.io/react/docs/forms.html Check the difference between controlled and uncontrolled components. – zerkms Aug 24 '15 at 04:13

18 Answers18

336

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} />
coffeduong
  • 1,443
  • 1
  • 10
  • 11
nitishagar
  • 9,038
  • 3
  • 28
  • 40
  • but I don't create the INPUT as class, it's created by React.createElement. So, how to set default – Yarin Nim Aug 24 '15 at 07:26
  • 7
    @YarinNim You can use `render` with the above `` element. The `defaultChecked` can be provided as a param like `checked` is. – nitishagar Aug 24 '15 at 08:40
  • 1
    this is really strange. I am just fixing a bug that a `checkbox` is not checked by default because someone used `defaultChecked` instead of just `checked`. I changed it to `checked` and the issue is fixed. Probably something has changed since 2015 - or Formik messes up with `defaultChecked`. – schlingel Mar 26 '21 at 15:07
175

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((state) => !state)}
      />
      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((state) => ({isChecked: !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.

Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
Jon Saw
  • 7,599
  • 6
  • 48
  • 57
61

If the checkbox is created only with React.createElement then the property defaultChecked is used.

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

Credit to @nash_ag

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
Yarin Nim
  • 3,607
  • 3
  • 14
  • 15
43

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

Murtaza Hussain
  • 3,851
  • 24
  • 30
  • 1
    if you use checked parameter directly you can't able to uncheck it. for this defaultChecked parameter has to be used. thanks. – kodmanyagha Jan 06 '20 at 12:24
14

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

<input name="remember" type="checkbox" defaultChecked/>
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
  • 1
    Should be the accepted answer, as this is what most people will be looking for: an alternative to the native HTML `checked`. – Bram Vanroy Aug 06 '18 at 09:31
8

Value would be whether true or false defaultChecked={true}

<input type="checkbox"
        defaultChecked={true}
        onChange={() => setChecked(!checked)}
      />
MD SHAYON
  • 7,001
  • 45
  • 38
8
import React, { useState } from 'react'


const [rememberUser, setRememberUser] = useState(true) //use false for unchecked initially


<input
   type="checkbox"
   checked={rememberUser}
   onChange={() => {
      setRememberUser(!rememberUser)
   }}
/>

August Kimo
  • 1,503
  • 8
  • 17
5

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 })}
user2061097
  • 51
  • 1
  • 2
5

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>
ponteskl
  • 59
  • 1
  • 1
  • You should not do this. If you pass a string to the "checked" property you will get the warning: **"Warning: Received the string `true` for the boolean attribute `checked`. Although this works, it will not work as expected if you pass the string "false". Did you mean checked={true}?"** – paul.ago Jun 06 '19 at 15:34
3

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>
    )
}

}

1

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

Southpaw
  • 73
  • 1
  • 1
  • 8
1

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})}
1

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>
         )
      }
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
vinny
  • 360
  • 3
  • 10
0

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>
Md Fazlul Karim
  • 355
  • 7
  • 15
0
<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)
    }
  };
  • 1
    Some accompanying text would help to understand what your code snippet is meant to do and how it relates to the question about ReactJS. – Xypron Oct 19 '20 at 20:46
0

You can use a state var "enableSwitch" and a function "handleSwitch" to handle your default checked Switch:

<div class="custom-control custom-switch">
    <input type="checkbox" class="custom-control-input" id="switchId" checked={this.state.enableSwitch} onClick={this.handleSwitch}/>
    <label class="custom-control-label" for="switchId">switch text</label>
</div>

Here's the function which inverts the variable if the user clicks on the switch:

handleSwitch = (e) => {
   this.setState({ enableSwitch: !this.state.enableSwitch });
}

I know it's a late reply to an old question, but this short solution may help other users.

Redaniat
  • 43
  • 7
-2
 <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

user2903536
  • 1,716
  • 18
  • 25
-2

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 :)

Sachin R
  • 43
  • 2