Home > Mobile >  How to write a conditional css pseudo-element with styled-components?
How to write a conditional css pseudo-element with styled-components?

Time:11-11

I am trying to write a styled-component with conditional pseudo-elements, but it does not seem to be working. Is this the correct syntax?

Context: I am trying to make it so that, if isSelected === true, a second, red-colored, border appears around my div (a rectangular box with a black border).

Much thanks!

const CardContainer = styled.div(
    (props) => css`
        align-self: center;
        margin: auto;
        width: 80%;
        height: 100%;
        background: rgb(222, 222, 222);
        border-style: solid;
        border-width: 0.1rem;
        box-shadow: 4px 4px 8px rgba(183, 183, 183, 0.25);

        ${props.isSelected &&
        css`
            &::before {
                border-color: red;
                border-style: solid;
                border-width: 0.1rem;
            }
        `}
    `
);

CodePudding user response:

it does not seem to be working.

The syntax itself is alright, but you are missing the content prop. content is essential, because unless specified, the pseudo element will not appear.

&::before {
    border-color: red;
    border-style: solid;
    border-width: 0.1rem;
    content: 'abc'; // it can be anything, even empty string
}

https://codesandbox.io/s/sad-sound-j5czon?file=/src/App.js:385-506

  • Related