Custom radio button with styled-components
1 min read

Custom radio button with styled-components

How to create a really customizable raido button with styled-components? Here's an approach I'm using.

const HiddenRadioButton = styled.input.attrs({
  type: "radio",
})`
  height: 25px;
  width: 25px;
  cursor: pointer;
  position: absolute;
  opacity: 0;
`;

const RadioButton = styled.span`
  width: 13px;
  height: 13px;
  border-radius: 50%;
  background-color: white;
  pointer-events: none;

  ${HiddenRadioButton}:checked + && {
    background-color: red;
  }
`;

One hidden raido button for interaction, another button for customization, and it changes appearance based on the checked state of the hidden one. It's more flexilbe than styling a raido button directly.

Notice here we are using && to reference the static class of RadioButton.

Each node actually has two classes connected to it: one is static per component, meaning each element of a styled component has this class. The static class probably will look something like: .sc-fVOeaW.

The other is dynamic, meaning it will be different for every element of your styled component with different props, based on what the interpolations result in. It will probably look like .fVOeaW (note the lack of "sc" prefix.)

Enjoying these posts? Subscribe for more