How to set default Checked in checkbox ReactJS?

When working with checkboxes in ReactJS, you may come across the need to set a default checked value. In this blog post, we will explore two different solutions to achieve this.

Solution 1: Using the defaultChecked attribute

The simplest way to set a default checked value in a checkbox component is by using the defaultChecked attribute. This attribute allows you to specify whether the checkbox should be checked by default.

Here’s an example:

{`import React from 'react';

function CheckboxExample() {
  return (
    
); } export default CheckboxExample;`}

In the above code snippet, the defaultChecked attribute is added to the input element. This will set the checkbox to be checked by default when the component is rendered.

Solution 2: Using the checked state

If you need more control over the checked state of the checkbox, you can use the checked attribute along with the component’s state. This allows you to dynamically set the checked value based on some condition.

Here’s an example:

{`import React, { useState } from 'react';

function CheckboxExample() {
  const [isChecked, setIsChecked] = useState(true);

  const handleCheckboxChange = () => {
    setIsChecked(!isChecked);
  };

  return (
    
); } export default CheckboxExample;`}

In the above code snippet, we use the useState hook to create a state variable called isChecked. The initial value of isChecked is set to true, making the checkbox checked by default.

The checked attribute of the input element is then set to the isChecked state variable. This ensures that the checkbox reflects the current value of isChecked.

Additionally, we define a handleCheckboxChange function that toggles the value of isChecked when the checkbox is clicked. This allows the checkbox to be dynamically checked or unchecked based on user interaction.

Both of these solutions provide a way to set a default checked value in a checkbox component in ReactJS. Choose the one that best suits your needs and enjoy building your React applications!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *