How to render pseudo before content dynamically in styled-component

user5809117 picture user5809117 · Sep 21, 2017 · Viewed 7k times · Source

I'm having a trouble of rendering pseudo before content dynamically in styled-components.

Am I doing something wrong?

I have no problem when I render pseudo before content statically, but it doesn't work when I try it dynamically.

React Component

const Test = (props) => {

    return (
        <Text before={12345}>
            {props.children}
        </Text>
    );

};

Styled Component(Not Work)

const Text = styled.span`

    &:before {
        content: ${props => {
            console.log(props.before); // I see '12345' in log.
            return props.before;
            }
    }


`;

Styled Component(This works fine)

const Text = styled.span`

    &:before {
        content: '12345'
    }


`;

Answer

Matthew Barbara picture Matthew Barbara · Sep 22, 2017

That is because content value must be within quotes in css

Here is a working CSS

const Block = styled.div`
    &:before {
        display: absolute;
        top:0;
        content: '${props => props.before}'
    }
`

Please note that I am leveraging ES6 new features wherein a single statement function there is no need to use curly braces {} and return.

Codepen: https://codepen.io/metju/pen/zEKeOm