Steps to design a unique input radio button with embedded attributes

In my current project, I am utilizing react styled components for styling. One issue that I have encountered is with the text placement within a box and the need to style it differently when checked.

What have I attempted so far?

I created an outer div and placed a radio input inside it with a display:none property. My intention was to style the outer element while keeping the radio button hidden. However, this approach rendered the radio button unclickable. Is there a solution to this problem? A react-specific solution would be highly appreciated.

.radio__input{
  display:none;
}

.radiobox{
  width:60px;
  height:60px;
  border:1px solid black;
}
//I want the div radiobox to be styled when one radiobox is selected

<div class="radiobox">
  <input type="radio" class="radio__input" name="radio"/>
  XS
</div>
<div class="radiobox">
  <input type="radio" class="radio__input" name="radio"/>
  S
</div>

https://i.sstatic.net/twwD4.png

Answer №1

I have implemented unique IDs for each radio button, allowing the <label> element's for attribute to link the labels with the corresponding radio buttons. This setup ensures that clicking on the label also checks the associated input. After setting up the functionality, I proceeded to style the radio buttons in their initial and checked states. It is important to note that CSS can only target elements based on the checked state of an input if they are siblings or children. Unfortunately, directly styling a parent element like the .radiobox container using pure CSS is not possible.

.radiobox {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid;
  display: flex;
  justify-content: center;
  align-items: center;
  display: inline-block;
}

input[type="radio"] {
  appearance: none;
}

input[type="radio"] + label {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

input[type="radio"]:checked + label {
  background: blue;
}
<div class="radiobox">
  <input type="radio" id="s" name="radio"/>
  <label for="s">S</label>
</div>

<div class="radiobox">
  <input type="radio" id="m" name="radio"/>
  <label for="m">M</label>
</div>

Answer №2

It is vital to have the radio button accessible while still maintaining its functionality.

An effective way to style radio buttons is by targeting their <label> element and using the CSS Adjacent sibling combinator based on the radio button's state.

Considerations for improving accessibility include:

  • Using <fieldset> to give an accessible name to the option group, even if it seems self-explanatory like "Green"
  • Ensuring focus visibility, which can be achieved by displaying the radio button within the fieldset
  • Providing each radio button with an accessible name, including hidden text inside labels

.color-options {
  display: flex;
  padding: .2em;
  gap: .4em;
}

.color-options:focus-within {
  outline: .2em solid blue;
}

.color-option {
  width: 2em;
  height: 2em;
}

input:checked+.color-option {
  outline: .2em solid darkseagreen;
}

/* credits to Scott O'Hara 
   https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html */
.visually-hidden {
  clip: rect(0 0 0 0);
  clip-path: inset(50%);
  height: 1px;
  overflow: hidden;
  position: absolute;
  white-space: nowrap;
  width: 1px;
}
<fieldset>
  <legend>Color</legend>

  <div class="color-options">
    <input type="radio" name="color" value="gray" id="color-gray" class="visually-hidden">
    <label class="color-option" style="background-color: gray" for="color-gray">
    <span class="visually-hidden">
    Gray
    </span>
  </label>

    <input type="radio" name="color" value="black" id="color-black" class="visually-hidden">
    <label class="color-option" style="background-color: black" for="color-black">
    <span class="visually-hidden">
    Black
    </span>
  </label>

    <input type="radio" name="color" value="darkgreen" id="color-darkgreen" class="visually-hidden">
    <label class="color-option" style="background-color: darkgreen" for="color-darkgreen">
    <span class="visually-hidden">
    Dark Green
    </span>
  </label>

  </div>
</fieldset>

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

Transmit a message from the background.js script to the popup window

Currently, I am looking to integrate FCM (Firebase Cloud Messaging) into my chrome extension. After conducting thorough research, I have discovered that the most efficient way to implement FCM is by utilizing the old API chrome.gcm. So far, this method has ...

What steps should I take to troubleshoot the 'TypeError: userId is not a function' error in my unban feature?

I am currently working on implementing an unban feature for my bot, however, I am encountering issues whenever I try to test the command (!unban <userId>). Instead of the expected outcome, I am faced with an error which is detailed below. This snipp ...

Shut down React Modal

I'm facing issues in implementing a close button for my modal. The constructor/props method is not working as expected and I am unsure about the onClick attribute that needs to be added to the button element. class Modal extends React.Component { ...

Retrieve user details from a NextJS application following a successful Keycloak authentication on a Kubernetes cluster

I've been attempting to retrieve the authenticated user information in my NextJS app after being redirected to it following a successful Keycloak login on a different tab located at localhost:8080/auth. The ingress (entry point) is responsible for ch ...

CSS - Apply a captivating background to specific columns within a grid layout

Wow, I'm really struggling with CSS and this particular issue has me perplexed. I need to add background colors to specific columns but not all of them. The problem is that the padding gets messed up when I do this. Imagine having a headache while try ...

Tips for creating a condensed header

As a newcomer to HTML, I am facing challenges in creating a simple header similar to the one displayed on this website or the example in the image below. Below is the snippet of HTML that I have attempted: <header class="header"> <div ...

What is the best way to send a prop for inline styling in a React component that contains an array of data?

My ShowData component is responsible for rendering in both my App.js and index.js files. import React from "react"; import SwatchData from "./SwatchData"; import { DataTestContainer } from "./DataTestContainer"; function ShowData(props) { const DataCom ...

Ensuring props are resilient even when an incorrect type is provided during testing

In my development using the MERN stack and Redux, I encountered an issue while testing props on one of my components. Despite defining all types and running tests, they still pass even with incorrect data entered. I have tried specifying the shape of each ...

Challenges in aligning images side by side within an XSLT document

My XML file is currently being transformed using XSLT to display tables, but I would like these tables to be displayed next to each other in rows of three columns. However, the current output shows them displaying one after another vertically. Here's ...

The frontend forgets a user's logged-in status when the page is refreshed

Utilizing express, mongodb, redis, and mongoose as the backend for API services. On the front end, I employ react, react-router, and redux. Authentication is handled using sessionId along with cookie. For frontend authentication control, I utilize react ...

Unable to generate file with Compass

In my attempts to compile a project using compass, I have experimented with both the gui app and the command line. However, I consistently encounter the same error message in both cases: "Nothing to compile. If you're trying to start a new project, yo ...

retrieve all the table data cells except for the initial one

I have a specific table structure that I need to work with: <table> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td&g ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...

Functionality of the Parameters Object

As I transition from using the params hash in Rails to learning Node/Express, I find myself confused about how it all works. The Express.js documentation provides some insight: 'This property is an array containing properties mapped to the named rout ...

Generating random values from an array in PHP without the need to refresh the page

Lately, I've been delving into the world of PHP for the first time in a project. However, I've encountered a problem that has me stumped – despite scouring various questions on Stack Overflow. My issue involves randomizing values from an array ...

What is the best way to organize objects by their respective dates?

I am retrieving data from a database and I would like to organize the response by date. I need some assistance in grouping my data by date. Below is an example of the object I have: var DATA = [{ "foodId": "59031fdcd78c55b7ffda17fc", "qty" ...

What is the best way to execute multiple functions in sequence and halt the process if any of them encounter an error?

I am working with multiple Javascript functions that manipulate the DOM and run ajax requests. My goal is to execute these functions sequentially, one after the other, and only proceed if none of them return false from their ajax request. If any function r ...

Material UI AppBar displaying custom colors instead of theme colors

Currently, I am utilizing Material UI version 4.7.0. In my project, I have established a customized theme (shown below) by utilizing createMuiTheme() method with personalized primary and secondary colors set. Within my AppBar component (also displayed be ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Discover the process of dynamically importing JavaScript libraries, modules, and non-component elements within a Next.js

Lately, I have been utilizing Next.js and mastering its dynamic import feature for importing components with named exports. However, I recently encountered a particular npm package that functions only on the client-side (requires window) and has a substant ...