Search code examples
reactjsstyled-components

How to Style a React Child Component in a Parent Component in React?


If I have a Child Component like that:

const Div = styled.div`
  display: inline-block;
`;
const Div = styled.button`
  display: block;
  background-color: red;
  margin-left: auto;
  margin-right: auto;
`;
export default class Child extends React.Components{
  render(){
    return <Div><Button>Test</Button></Div>;
  }
}

And then I want to add Style to the Parent Component like that:

const Div = styled(Child)`
  margin-top: 10px;
`;
export default class Parent extends React.Components{
  render(){
    return <Child/>;
  }
}

So I guess this is the wrong approach to handle that? so is there another Way?


Solution

  • The answer is to add a Property className to the Parent Component and Apply them to the outer Element of Child Class. Then this is working. It is described here in Styled Components Docs: https://styled-components.com/docs/advanced#styling-normal-react-components