Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default Checked in checkbox 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} />

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.


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


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


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

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

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

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>