Search code examples
javascriptstyled-componentsemotion

Passing props along from styled component using Emotion.sh


I have the following styled button declared using @emotion\styled:

const Button = styled.button`
 background: blue;
 ${size({
  width: props => props.width
 )}
`

In my code, size is a function that returns size css serialized style based on the prop that is passed:


const size = ({ width: "m"} = {}) => {
 switch(width) {
  case "s":
   return css`width: 100px`;
  break;
  case "m":
   return css`width: 150px`;
  break;
 }
} 
<Button width="s">Some text</Button>

However, the width value that I receive in the size function is not the resolved value from the passed prop i.e. s, but rather it is a string props => props.width.

Is there any way to pass the props along into a function from a styled component similar to what I am trying to achieve?


Solution

  • It doesn't work since you're passing an anonymous function to width, in a place where you're not expecting a function.

    I'm pretty sure this is what you're trying to do:

    const Button = styled.button`
     background: blue;
     ${props => size({ width: props.width })}
    `
    

    This way, you're passing an anonymous function in the scope of the styled declaration, getting the props from Emotion and free to use it however you like.