EN
React - how to set default checked in checkbox?
1
answers
0
points
How can I set default checked in React checkbox?
I tried the following way but it won't let me uncheck the checkbox:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';
const Form = props => {
const [agreement, setAgreement] = React.useState(false);
const handleChange = e => setAgreement(e.target.checked);
const handleSubmit = e => {
e.preventDefault();
console.log(`checked: ${agreement}`);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
<input type="checkbox" checked={true} onChange={handleChange} />
<span>Consent to the data processing</span>
</label>
</div>
<button type="submit">Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );
1 answer
0
points
I found the solution:
There are two properties that you can use to set default 'checked' :
checked
property,defaultChecked
property.
I've changed the initial agreement
value in useState
to true
and assigned the value to the checked
property inside my checkbox.
Runnable example:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';
const Form = props => {
const [agreement, setAgreement] = React.useState(true);
const handleChange = e => setAgreement(e.target.checked);
const handleSubmit = e => {
e.preventDefault();
console.log(`checked: ${agreement}`);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
<input type="checkbox" checked={agreement} onChange={handleChange} />
<span>Consent to the data processing</span>
</label>
</div>
<button type="submit">Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );
Note:
You can use
defaultChecked
property instead ofchecked
to get the same result.
See also
0 comments
Add comment