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

Scrolling left and right, text floats atop the image

Trying to implement a rollover effect image using CSS. The initial state shows only the title, but upon hovering, a text overlay appears. Everything seems to be working well except that the text area extends off to the right. Also, there is scrolling up an ...

When working with Function components in NextJS, it's important to note that they cannot be assigned refs directly. If you're trying to access a ref within a Function component, you

I'm having an issue with wrapping a card component using the Link component from 'next/link'. Instead of redirecting me to the desired link when I click the card, I receive a warning that says 'Function components cannot be given refs. ...

Is the behavior of next/router determined by the specific Dom element that is clicked?

I've been working on implementing a dark mode/light mode hook and system for my platform using Next.js and React. Recently, I encountered a strange issue where clicking certain types of DOM elements causes a light mode flicker while others do not. Eve ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

The Bootstrap 4 navbar remains consistently visible on mobile devices

I am experiencing an issue with my bootstrap navbar on mobile devices. It remains visible even when the navbar-toggler is collapsed. Below is the code snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"&g ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

Effective Methods for Implementing CSS Variables within nth-child Selectors

Objective: To pass a variable successfully as a parameter to nth-child. The task is to make the third line turn green in the example provided. Dilemma: Currently, the parameter is being disregarded as a variable. Inquiry: Is achieving this possible? If s ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...

"Error: Failed to establish WebSocket connection" - Visual Studio Code and React Framework

Every time I start a new react project and run it on localhost:3000 using npm from either my Mac terminal or VSC terminal, I always encounter this error in my console. As a beginner in React development, I'm hoping someone can assist me in resolving t ...

Guide on how to efficiently navigate and extract data from a (local) XML file using Prototype JS

I'm currently working on a project that already utilizes PrototypeJS and I need to develop a module for it. Here's what I have: - An XML file containing the necessary information Here's what I'm aiming for: - A basic div that showcase ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

Displaying child properties in a functional ReactJS component

React version 0.14 introduces the concept of pure functional components, ensuring that the same input always results in the same output. Props are passed as function arguments. // Using ES6 arrow functions with implicit return: const PureComponent = ({url ...

Exploring the realms of development and production with Next JS and Vercel

I've recently developed a movie database application using Next JS to explore its functionality. This app allows users to create, read, update, and delete data in Firebase by utilizing the API endpoints provided by NextJS. While the app works smoothl ...

Top and bottom fieldset legends in Bootstrap 4

Looking for suggestions on how to include legend text on the bottom border in bootstrap 4. I attempted to use position and margin, but it didn't work. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.mi ...

Unknown CSS element discovered: bootstrap, gradient, carousel

I recently created a random quote app using javascript, jQuery, and bootstrap on Codepen. Everything worked perfectly there. However, when I organized the files, pushed them to git, and tried to view the app from Safari, I encountered some warnings and t ...

Why doesn't the 'theme' stay consistent in App.js when the hook function is invoked from a different component?

I developed a custom hook to switch MUI theming in my React application. It works perfectly when I change the theme from within App.js, but I encountered an issue when trying to trigger the "toggleDarkMode" function from another component: although the the ...

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

Creating a text shadow effect with text that has a transparent color

I am attempting to replicate the design shown below using the CSS text-shadow property, but I keep getting a solid color outcome. I have tried using an rgba value of 255,0,0,0.0 for the font-color and text-shadow like this: text-shadow: -1px -1px 0 #0 ...

Angular.js Issue: Repeating elements must be unique - Index tracking not functioning properly

I have been following a tutorial on the Ionic Framework, which utilizes Angular JS to develop a basic Todo application. The app adds a new task by utilizing the .push() method to append a new task object to an array of task objects. An issue arises when a ...