Languages

React - how to set default checked in checkbox?

0 points
Asked by:
maryam
251

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
Answered by:
maryam
251

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 of checked to get the same result. 

See also

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join