Setting variable in styled-components

Viewed 2685

I have a prop value that is used multiple times in the CSS decleration block.

Is it possible to set it to a variable initially to accomplish DRY:er code?

The following is a naive example, to show what I'm looking for. This doesn't work though - the variable size isn't accessible later on:

const Link = styled.a`
    ${props => {const size = props.size}};
    background-color: ${size === 'medium' ? 'palevioletred' : 'black'};
    width: 100%;
`;
2 Answers

Thinking out loud. Create a function which accepts some settings and returns the style.

Didn't test this snippet.

const getLinkStyle = ({size})=> {

    return styled.a`
        background-color: ${size === 'medium' ? 'palevioletred' : 'black'};
        width: 100%;
    `;
}

const Link = getLinkStyle(this.props)

I was also searching for something like that and came up with the idea to use a ThemeProvider. It is a little bit more boilerplate stuff, but it allows you to pass styles to multiples componentes from props. But you should be carful with nesting, as they overwrite the equal named attributes. And i think it can get very confusing if you put too much themes into each other.

class App extends Component {
    render() {
        return (
            <Container bgColor={'red'}/>
        );
    }
}

export default App;


function Container(props) {
    const bgColor = props.bgColor;
    const bgTheme = {bgColor: bgColor};

    return <ThemeProvider theme={bgTheme}>
        <div>
            <Div1/>
            <Div2/>
        </div>
    </ThemeProvider>
}

const Div1 = styled.div`
  background-color: ${props => props.theme.bgColor};
  margin: 10px;
  height: 50px;
  width: 50px;
`;

const Div2 = styled.div`
  background-color: ${props => props.theme.bgColor};
  margin: 10px;
  height: 50px;
  width: 150px;
`;
Related