Search code examples
styled-components

Create variable from props and reuse in code block with Styled Components?


Ive got a basic styled component working. When the prop isHere is passed then the background is blue.

const Item = styled.ul`
  ${props => console.log(props.theme.colorGroupSelected)};
  ${props => (props.isHere ? `background:` + 'blue' : null)};
`;

Instead of blue I need to use the colour colorGroupSelected from my theme but I cant get it to work, I keep getting a syntax error.

    const Item = styled.ul`
      ${props => (props.isHere ? `background:` + props => props.theme.colorGroupSelected : null)};
    `;

My code is getting quite hard to read. Is it possible to destructure a variable within a styled block? Something like this:

 ${const colorGroupSelected = (props => return props.theme.colorGroupSelected)};

 ${props => (props.isHere ? `background:` + colorGroupSelected : null)};

Solution

  • This works but doesn't destructure the variable:

     ${props => (props.isHere ? `background:` + props.theme.colorGroupSelected : null)};