How to change checkbox background color in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To change checkbox background color in react js, you can set background-color: #4CAF50; in .custom-checkbox input:checked + .checkmark. It will change checkbox background color in react js.

Today, I am going to show you, how to change checkbox background color in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React, { useState } from "react";
import "./App.css";

Step 3: Create a Component.

You can use className="custom-checkbox" to change checkbox background color in react js.

<label className="custom-checkbox">
  <input
    type="checkbox"
    checked={checked}
    onChange={() => setChecked(!checked)}
    />
  <span className="checkmark"></span>
</label>

Change checkbox background color example.

The below code is an example of a React. You have to import './App.css' and use background-color: #4CAF50; in .custom-checkbox input:checked + .checkmark. to change checkbox background color in react js.

App.js

import React, { useState } from "react";
import "./App.css";

const Checkbox = () => {
  const [checked, setChecked] = useState(false);

  return (
    <label className="custom-checkbox">
      <input
        type="checkbox"
        checked={checked}
        onChange={() => setChecked(!checked)}
      />
      <span className="checkmark"></span>
    </label>
  );
};

export default Checkbox;

App.css

.custom-checkbox {
  position: relative;
  display: inline-block;
  cursor: pointer;
  user-select: none;
}

.custom-checkbox input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.checkmark {
  width: 20px;
  height: 20px;
  background-color: #ccc; /* Default background color */
  border-radius: 4px;
  display: inline-block;
  vertical-align: middle;
  transition: background-color 0.3s;
}

.custom-checkbox input:checked + .checkmark {
  background-color: #4CAF50; /* Background color when checked */

}

.custom-checkbox input:checked + .checkmark:after {
  content: "";
  position: absolute;
  left: 6px;
  top: 2px;
  width: 6px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

In the above code example, I have used the background-color: #4CAF50; to change checkbox background color in react js.

Check the output of the above code.

React, checkbox, background, color

All the best πŸ‘