Search code examples
javascriptcssreactjsstyled-components

How can I use multiple props in a single callback defined in a template literal in React styled-components


I have started using styled components in my React project a couple of days back and I am not able to use multiple props to defined styles in my components. The gist of the problem goes like this:


const sizes = {
   lg: css`
        width: 200px;
        height: 120px;
        font-size: 22px;
    `,
    md: css`
        width: 140px;
        height: 80px;
        font-size: 18px;
    `
}
const getColor = (color)=>css`color: ${color}`

const MyComponent = styled.div`
 max-width: 240px;
 font-size: 12px;
 color: '#ffffff';
 ${props=>getColor(props.color)}
 ${props=>sizes[props.size]}
`
....

<MyComponent color="blue" size="lg" ></MyComponent>

The issue is, every time I need to add an extra config(like color and size) for my component, I'll have to add another callback in template literal.

Is there a way to apply everything with a single line of code and not add separate callbacks?


Solution

  • styled also accepts a function that passes props:

    const MyComponent = styled.div(({color, size}) => `
     max-width: 240px;
     font-size: 12px;
     color: ${color ? color : '#ffffff'};
     `${sizes[size]}`
    `
    

    I'm using destructuring but you can leave it as props if you prefer.