Search code examples
styled-components

How to change styles of react component using styled components


I have this React component which is a simple button component:

const Button = ({ children }) => <button>{children}</button>;

I tried to pass the above component inside a styled in order to try to change its styles like this:

const StyledButton = styled(Button)`
  color: yellow; //does not work

  button {
    color: yellowgreen; //does not work
  }
`;

I am new to styled components so I am not even sure this is possible to do.

Thank you in advance for the help!


Solution

  • When using styled-components for your custom React components, styled-components needs to know where to inject the CSS you want to give to your <button> tag. This is done by passing the className prop to your Button component and passing it as a prop to the <button> tag.

    Please try to edit your code like so:

    const Button = ({ children, className }) => <button className={className}>{children}</button>;
    

    You can read more about it here Styled Components - Existing CSS.