Search code examples
javascriptcssreactjsstylesemotion-js

React emotion styled not working but normal css was working fine for input and label styles


Everything is working except this piece which I have tried many different ways...

    const HiddenInput = styled.input`
    display: none;
    &:checked + CheckboxLabel: {
        background-color: #866dce;
    },
`

The checked should change color but it doesn't. I also tried using .checkbox-label where classname='checkbox-label" but no luck

Here is the relevant code...

const CheckboxLabel = styled.label`
    background-color: rgb(211, 106, 106);
    cursor: pointer;
    font-size: 20;
    text-align: center;
    display: flex;
    justify-content: center;
    margin-right: 10px;
    padding: 5px;
    border-radius: 5px;
`
const HiddenInput = styled.input`
    display: none;
    &:checked + .checkbox-label: {
        background-color: #866dce;
    }
`

<HiddenInput type="checkbox" id={"toggle"+index} onChange={() => handleChecked(item)} key={"input" + index} />
<CheckboxLabel htmlFor={"toggle"+index} className="checkbox-label" key={"label" + index}>{item}</CheckboxLabel><br />

Solution

  • you need to wrap the component with ${}. Also there's a scss syntax error, you had to remove : from the front of your selection element:

        const HiddenInput = styled.input`
          display: none;
          &:checked + ${CheckboxLabel} {
            background-color: #866dce;
          },
    `
    

    note: you can use babel-macro that's included by default in create-react-app

    import styled from '@emotion/styled/macro'
    

    emotions