Search code examples
reactjsstyled-components

React: how to refer to child of styled-component by its name


Is there a way to refer to sub-component of styled-component by its name? Or, besides passing hardcoded className and refer to it instead there's no way around it?

const Parent = styled.div`
  // some styles

  & > Child1 {
    opacity: 1;
  }

`;

const Child1 = styled.div`
  opacity: 0;
`;

const Child2 = styled.div`
  opacity: 0;
`;


const App = (props: Props) => (
  <Parent>
    <Child1 />
    <Child2 />
  </Parent>
)

Solution

  • Umm you have the ${} missing in your styles. Also you might want to place the const Parent after declaring the Child1.

    const Child1 = styled.div`
      opacity: 0;
    `;
    
    const Child2 = styled.div`
      opacity: 0;
    `;
    
    const Parent = styled.div`
      // some styles
    
      & > ${Child1} {
        opacity: 1;
      }
    
    `;
    
    
    const App = (props: Props) => (
      <Parent>
        <Child1 />
        <Child2 />
      </Parent>
    )
    

    If you wanna explore more about template literals here's a link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals