WichyCake
WichyCake

Reputation: 616

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>
)

Upvotes: 1

Views: 57

Answers (1)

Subhendu Kundu
Subhendu Kundu

Reputation: 3856

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

Upvotes: 2

Related Questions