Search code examples
reactjsthemesstyled-componentstheming

Override them with styled components


I want to creare a template theme in React for my software suite and allow developers to customize the theme for each software they develop.

The theme will be shipped in a library using styled components

Here is an example of the code:

import styled from 'styled-components'

const ButtonStyled = styled.button`
  font-size: 1.5em;
  text-align: center;
  color: green;
`;

const TomatoButton = styled(ButtonStyled)`
  color: tomato;
`;

//This is the default template
const DefaultTemplate = () => {
  return <div>
    <ButtonStyled className='button'>Button</ButtonStyled>
    <TomatoButton className='tomato-button'>Button II</TomatoButton>
  </div>
}

//This is the template styled by developers
const DefaultTemplateStyled = styled(DefaultTemplate)`
  color: white;

  &.button{
    color: violet
  }

  &.tomato-button{
    color: black;
  }
`;

function App() {
  return (<DefaultTemplateStyled />);
}

export default App;

In this app I cannot see the override of the styles, am I missing something?


Solution

  • In styled-components what you should do is pass the className propm like this:

    //This is the default template
    const DefaultTemplate = ({ className }) => {
      return (
        <div>
          <ButtonStyled className={`button ${className}`}>Button</ButtonStyled>
          <TomatoButton className={`tomato-button ${className}`}>
            Button II
          </TomatoButton>
        </div>
      );
    };
    

    All the other code is fine