How to set default Checked in checkbox ReactJS?

ReactjsCheckbox

Reactjs Problem Overview


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.

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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.

Solution 3 - Reactjs

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

Solution 4 - Reactjs

> 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

Solution 5 - Reactjs

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

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

Solution 6 - Reactjs

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>

Solution 7 - Reactjs

import React, { useState } from 'react'


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


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

Solution 8 - Reactjs

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

Solution 9 - Reactjs

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

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

Solution 10 - Reactjs

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

}

Solution 11 - Reactjs

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

Solution 12 - Reactjs

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

Solution 13 - Reactjs

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

Solution 14 - Reactjs

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>

Solution 15 - Reactjs

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

Solution 16 - Reactjs

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.

Solution 17 - Reactjs

 <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

Solution 18 - Reactjs

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYarin NimView Question on Stackoverflow
Solution 1 - ReactjsnitishagarView Answer on Stackoverflow
Solution 2 - ReactjsJon SawView Answer on Stackoverflow
Solution 3 - ReactjsYarin NimView Answer on Stackoverflow
Solution 4 - ReactjsMurtaza HussainView Answer on Stackoverflow
Solution 5 - ReactjsFareed AlnamroutiView Answer on Stackoverflow
Solution 6 - ReactjspontesklView Answer on Stackoverflow
Solution 7 - ReactjsAugust KimoView Answer on Stackoverflow
Solution 8 - Reactjsuser2061097View Answer on Stackoverflow
Solution 9 - ReactjsMD SHAYONView Answer on Stackoverflow
Solution 10 - ReactjsGOKUL KANNAMBALLY BALACHNADRANView Answer on Stackoverflow
Solution 11 - ReactjsSouthpawView Answer on Stackoverflow
Solution 12 - ReactjsRishijay ShrivastavaView Answer on Stackoverflow
Solution 13 - ReactjsvinnyView Answer on Stackoverflow
Solution 14 - ReactjsMd Fazlul KarimView Answer on Stackoverflow
Solution 15 - ReactjsAyoub WazaneView Answer on Stackoverflow
Solution 16 - ReactjsRedaniatView Answer on Stackoverflow
Solution 17 - Reactjsuser2903536View Answer on Stackoverflow
Solution 18 - ReactjsSachin RView Answer on Stackoverflow