Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS + styled components + pseudoClasses

Tags:

reactjs

Is it possible to use pseudoclasses for styling components. I have checkbox which should display SVG image: checked/ unechecked for displaying state as selected/unselected. I can do this with passing props from parent. But i have been told it is possible by only css(styled components). part of my code:

 const CheckboxInput = styled.input`
  &:checked, &:not(:checked) {
  display: none;
 }`;

const CheckboxLabel = styled.label`
  cursor: pointer;
  -webkit-user-select: none; /* Chrome/Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
`;

function Checkbox(props) {
  return (
    <CheckboxLabel htmlFor="id" onChange={() => { props.onchange(); }}>
      <CheckboxInput id="id" type="checkbox" checked={props.checked} value="cb" name="cb" />
      <Span><SVG glyph={checked} width={17} height={17} /></Span>
      <Span><SVG glyph={unchecked} width={17} height={17} /></Span>
      {props.children}
    </CheckboxLabel>
  );
}
like image 713
palyxk Avatar asked Oct 24 '25 19:10

palyxk


1 Answers

With following selector in styled-components you can use the state of the input/checkbox to modify the style with only CSS:

  &:checked + ${Label} {
    /* your CSS */
  }

Here is a full example:

import React from 'react';
import { render } from 'react-dom';
import styled from 'styled-components';


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>
);

render(<App />, document.getElementById('root'));

You can see a preview of it here: https://codesandbox.io/s/oYQ21A4wz

This should give you a basic idea how to change style with CSS only.

like image 140
glennreyes Avatar answered Oct 26 '25 09:10

glennreyes