MestreALMO
MestreALMO

Reputation: 171

How to style a label when input inside it is checked?

Right here I've a code where I change the label's background when input is checked, but label is right after the input, as displayed in the following example.

const Label = styled.label`
  background: red;
  display: block;
  padding: 1rem;
`;

const Input = styled.input`
  &:checked + ${Label} {
    background: blue;
  }
`;

const App = () => (
  <div>
    <Input id="input" type="checkbox" />
    <Label for="input" />
  </div>
);

But how would it be possible to change the label background if the input was inside the label? as displayed in the example below:

const App = () => (
  <div>
    <Label for="input" />
       <Input id="input" type="checkbox" />
    </Label>
  </div>
);

Upvotes: 1

Views: 1120

Answers (1)

Anton
Anton

Reputation: 8508

You can't use the bubbling stage in css like also styled-components. But you can get event from input and then pass in styled-component. example

import { useState } from "react";
import styled from "styled-components";

const Label = styled.label`
  background: ${({ checked }) => (checked ? "blue" : "red")};
  display: block;
  padding: 1rem;
`;

const Input = styled.input`
  /* &:checked + ${Label} {
    background: blue;
  } */
`;

export default function App() {
  const [checked, setChecked] = useState(false);
  const toggle = () => setChecked(!checked);
  return (
    <div className="App">
      <Label for="input" checked={checked}>
        <Input id="input" type="checkbox" onChange={toggle} />
      </Label>
    </div>
  );
}

Upvotes: 1

Related Questions