React, styled-components - style inner styled-component

Viewed 54

I have a demo

https://stackblitz.com/edit/react-ts-jvbeh7

It's a simple react app using styled-components

I'm passing a prop desktop

<Block desktop>
    <InnerBlock />
</Block>

And I'm trying to style the inner style component when the prop is there

const Block = styled.div<IProps>`
  background: red;
  height: 200px;
  width: 200px;

  ${InnerBlock} {
    margin: ${p => p.desktop ? '10px' : null};
  }

`;

If I try this I get an error on ${InnerBlock}

Block-scoped variable 'InnerBlock' used before its declaration. 

Is it possible to style an inner styled-component <InnerBlock /> when there is a prop on the parent

1 Answers

Found the correct way.

const Block = styled.div<IProps>`
  background: red;
  height: 200px;
  width: 200px;

  ${InnerBlock} {
    ${(p) =>
      p.desktop &&
      css`
      width: 50px;
      height: 50px;
      background: yellow;
    `};
  }

`;
Related