276

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.

1

20 Answers 20

350

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} />
Sign up to request clarification or add additional context in comments.

3 Comments

but I don't create the INPUT as class, it's created by React.createElement. So, how to set default
@YarinNim You can use render with the above <input> element. The defaultChecked can be provided as a param like checked is.
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.
180

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.

5 Comments

State-full! How about stateless approach?
This doesn't work anymore, throws the unhandled input error
Tested it & it's working fine on my end. Do you have any additional info @user6329530?
This works, but defaultChecked is better.
I would recommend you do the setState like this onChange={() => setChecked(prevState => !prevState)}
64

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

2 Comments

this is not right you can use defaultChecked also with normal html tag, same as (class => className) and (for => htmlFor) and so on ...
@FareedAlnamrouti these statements are not mutually exclusive. Yarin is saying defaultChecked is needed if using React.createElement, not that it's used for that exclusively.
46

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

1 Comment

if you use checked parameter directly you can't able to uncheck it. for this defaultChecked parameter has to be used. thanks.
16

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

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

1 Comment

Should be the accepted answer, as this is what most people will be looking for: an alternative to the native HTML checked.
8

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

<input type="checkbox"
        defaultChecked={true}
        onChange={() => setChecked(!checked)}
      />

Comments

8
import React, { useState } from 'react'


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


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

4 Comments

checked will render readonly checkbox
No it won't, try it.
I have checked that. if you checked attribute in react js it will render a read-only checkbox. you cannot check or uncheck if you use the checked attribute. better to use defaultChecked.
@RahulMore if you use a checked prop without onChange it will render a read-only field.
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 })}

Comments

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>

1 Comment

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

}

Comments

3

The input type=checkbox has its own properties defaultChecked and checked.

defaultChecked is used to specify the initial value you want to display.

checked is used to determine the current checked status.

const [checked, setChecked] = useState(false);

<input type="checkbox" defaultChecked="true" checked=""onChange={(e)=>{setChecked(e.target.checked) }} />

Comments

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

2 Comments

Yet another... This is state-full approach! How about stateless?
Green, what do you mean ?
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})}

Comments

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

Comments

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>

Comments

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 Comment

Some accompanying text would help to understand what your code snippet is meant to do and how it relates to the question about ReactJS.
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.

Comments

0

By utilizing isChecked and setChecked

 const SomePage=()=>{
   const [isChecked,setChecked ] =useState(false);
   const onChangeEvent=(e)=>{
     setChecked(e.target.checked);
   };

   return(<div>
     <input type="checkbox" checked={isChecked} onChange= 
     {(e) => onChangeEvent(e)} />   
     </div>);
    };

Comments

-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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.