Customizing checkboxes in React with JSS: A step-by-step guide

I'm currently working on customizing CSS using JSS as my styling solution, which is proving to be a bit complex while following the w3schools tutorial.

https://www.w3schools.com/howto/howto_css_custom_checkbox.asp

HTML:

<label class="container">One
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>

CSS:


/* Customizes the label (the container) */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hides default browser checkbox */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

/* Creates custom checkbox */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}

/* Adds grey background color on mouse-over */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}

/* Provides blue background when checkbox is checked */
.container input:checked ~ .checkmark {
  background-color: #2196F3;
}

/* Displays checkmark/indicator when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

Answer â„–1

Using JSS, you can customize checkboxes in React by nesting components.

Check out this example on CodeSandbox

Here's how to style checkboxes in React using JSS:

import React from "react";
import { createUseStyles } from "react-jss";

// Check out this guide for more info: https://www.w3schools.com/howto/howto_css_custom_checkbox.asp

import "./styles.css";

const useStyles = createUseStyles({
  /* Customize the label (the container) */
  container: {
    display: "block",
    position: "relative",
    paddingLeft: "35px",
    marginBottom: "12px",
    cursor: "pointer",
    fontSize: "22px",
    userSelect: "none",
    "& input": {
      /*  Hide the browser's default checkbox  */
      position: "absolute",
      opacity: 0,
      cursor: "pointer",
      height: 0,
      width: 0,
      /* Show the checkmark when checked */
      "&:checked": {
        "& ~ $checkmark": {
          backgroundColor: "#2196F3", /* Add blue background when checked */
          "&:after": {
            display: "block"
          }
        }
      }
    },

    "& $checkmark": {
      "&:after": {
        left: "9px",
        top: "5px",
        width: "5px",
        height: "10px",
        border: "solid white",
        borderWidth: "0 3px 3px 0",
        transform: "rotate(45deg)"
      }
    },

    "&:hover": { /* Grey background on mouse-over */
      "& input": {
        "& ~ $checkmark": {
          backgroundColor: "#ccc"
        }
      }
    }
  },

  checkmark: {
    position: "absolute",
    top: 0,
    left: 0,
    height: "25px",
    width: "25px",
    backgroundColor: "#eee",
    "&:after": {
      content: '""',
      position: "absolute",
      display: "none"
    }
  }
});

export default function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <h1>How to customize checkbox with JSS</h1>

      <label className={classes.container}>
        One
        <input type="checkbox" checked={true} />
        <span className={classes.checkmark} />
      </label>
      <label className={classes.container}>
        Two
        <input type="checkbox" checked={false} />
        <span className={classes.checkmark} />
      </label>
      <label className={classes.container}>
        Three
        <input type="checkbox" />
        <span className={classes.checkmark} />
      </label>
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to enhance the accessibility of a dynamically generated file by implementing the ability to expand and collapse sections as parent nodes

Currently working on a webpage where I am showcasing a testsuite file as the parent node and test cases within the testsuite file as child nodes. I have added checkboxes to both the parent and child nodes. Now, my goal is to include an ex ...

I'm looking to include a field card into the to-do table I built using .Net, but I'm not sure where I made a mistake

HTML Challenge I have set a goal to dynamically add a DOM element using JavaScript when the "Add HTML Element" button is clicked. The process involves clicking the button, which opens a modal for inputting necessary information. After fil ...

The attribute 'positive_rule' is not found within the structure '{ addMore(): void; remove(index: any): void;'

data() { return { positive_rule: [ { positive_rule: "", }, ], }; }, methods: { addMore() { this.positive_rule.push({ positive_rule: "", }); }, ...

Enabling the execution of returned scripts using JQuery AJAX

I have a hyperlink that I need to send a DELETE request using JQuery through AJAX. if(confirm("Do you wish to proceed?")) { $.ajax({ url: $(this).attr("href"), type: 'DELETE', success: function(result) { // Perform act ...

I encountered an issue while trying to make a request, receiving an ERROR with status code 404 in AxiosError

I've encountered an issue with my small web app built using React, Express, MongoDB, and Node. I'm utilizing Axios for interactions with Mongo/Express. The problem lies in a component that is intended to fetch data from Mongo but appears to be tr ...

Discover the HTML of a different website using Javascript

I'm currently developing a basic webcrawler that will display all the links found on a specified website. Here's what I envision my program doing: - enter a URL: http://www.example.com/ - the program retrieves the HTML source and locates all th ...

Trouble with top attribute functionality within animate function

Why does the top attribute in the animate function of JQuery not seem to work, while the opacity attribute functions correctly in the code snippet below? $(function() { $(window).on('scroll', function() { ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Encountering an issue in the test file when using react-router-dom v6: "The 'history' property is not found on the 'IntrinsicAttributes & RouterProps' type."

Main script: import { useContext, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import AuthenticationContext from './AuthenticationContext'; function HandleOAuthCallbackRoute() { co ...

Integrating threejs dynamically into a Create React App environment

When I am dynamically loading Three.js, the variable THREE is not found. I have created a React project using create-react-app and copied the three js file into the public folder. Here's the directory structure: src public ├── js │ └─┠...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Press the Text and Alter Text with React

I'm having an issue with the onClick event using React hooks. My goal is to have the text change to a different one when the user clicks, and then revert back to the original text on another click. For example, clicking "Change First" should switch it ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...

React JS offers a convenient way to create dependent select components

This is a code snippet that demonstrates the use of two select elements: <select> <option>1</option> <option>2</option> <option>3</option> </select> The second select element is as follows: <sel ...

What is the best way to store a downloaded video from the server?

I am currently in the process of downloading a video from a server using JavaScript XHR (specifically Angular $http GET with response type 'blob'). My question is, how can I save this downloaded video to a Chrome application's local storage ...

Splitting elements into two categories with Angular.JS: Comparing ng-hide and filter

My task is to take an object with data and display it in two separate lists. The structure of the object is as follows: var data = [ {name: "Something 1", active: 1, datetime: "goes", author: "here"}, {name: "Something 2", active: 0, datetime: "goes ...

Using localStorage in the client side of nextJS is a breeze

Encountering an error while attempting to retrieve local storage data. Even with the use client directive in place at the beginning, the issue persists. 'use client'; const baseURL = 'https://localhost:7264'; const accessToken = localSt ...

What are the best practices for using .toString() safely?

Is it necessary for the value to return toString() in order to call value.toString()? How can you determine when you are able to call value.toString()? <script> var customList = function(val, lst) { return { value: val, tail: lst, t ...

What is an alternative method to retrieve form data without relying on bodyParser?

When it comes to accessing posted form data without using bodyParser, what alternatives are available? How exactly does bodyParser grant access to the data in req.body? Additionally, I am curious about the inner workings of this process on a deeper level. ...