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