Search code examples
reactjsstyled-components

Styled-components add styles to custom component


I want to add styles to the custom component with a help of the styled-components library. I found some similar questions on StackOverflow with answers but it seems not to work for me. I do something like this:

  1. Here is my custom component
const ComponentStyledBox = styled.div`
  color: red;
`;

const ComponentStyled = () => (
  <ComponentStyledBox>Component With StyledComponents</ComponentStyledBox>
);
  1. And here I try to use my custom component and add some styles to it
const ComponentStyledWrapper = styled(ComponentStyled)`
  background-color: green;
`;

export default function App() {
  return (
    <div>
      <ComponentStyledWrapper />
    </div>
  );
}

As the result, I don't have a green background. Only red text. The same will be if I use instead of the styled custom component just a component with styles added via CSS in a common way. What do I do wrong?

For your convenience here is a CodeSandbox

Thanks in advance!


Solution

  • The problem is caused by this:

    const ComponentStyled = () => (
      <ComponentStyledBox>Component With StyledComponents</ComponentStyledBox>
    );
    

    You've defined a new component called ComponentStyled which is not style-able. Try this instead (in App.styles.tsx):

    import { ComponentStyledBox } from "./components/ComponentStyled/ComponentStyled.styles";
    
    export const ComponentStyledWrapper = styled(ComponentStyledBox)`
      background-color: green;
    `;
    

    ComponentStyledBox is style-able, so you'll get the green background.

    Edit (response to @zakharov.arthur's comment): If really do want a custom component with hard-coded children (are you sure this is what you want?), you can make your custom component style-able by exposing ComponentStyledBox's props:

    // I haven't actually tried this but it should work.
    const ComponentStyled = (props: Omit<Parameters<ComponentStyledBox>[0], 'children'>) =>
      <ComponentStyledBox {...props}>Component With StyledComponents</ComponentStyledBox>