1

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!

zakharov.arthur
  • 187
  • 2
  • 13

1 Answers1

0

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>
Matthew
  • 28,056
  • 26
  • 104
  • 170
  • But just a short update question. So I can add styles with styled-components only to components that were created with styled["someTag"]`...`? And if I need to wrap and customize a component that is just a regular component then it is not possible? But I saw like guys were updating some component let's say from Material-UI by wrapping imported Button from the library. – zakharov.arthur Feb 02 '22 at 10:41
  • At the same time if I do so, then I will have my content lost. I mean the text from ComponentStyled is lost... – zakharov.arthur Feb 02 '22 at 10:49
  • @zakharov.arthur: See my edit for a solution – Matthew Feb 04 '22 at 21:05