Search code examples
javascriptcssreactjsstyled-components

styled components / react


Im working on a simple button example which i plan to extend. I have added a new button and included some constants as well. so far so good. In case i want to use more button versions like version1, version2, version3 of the same button with some styles changed like the background color. How should i do that? And how should they be exported?

const PrimaryButton = styled.button`
  font: inherit;
  padding: 0.5em 1em;
  border: 1px solid;
  background-color: ${buttonBackgroundColor};
  color: ${buttonColor};
  border-radius: 0.25em;
  border-color: ${colors.blueLight};
  margin-right: 0.5em;
  cursor: pointer;
  outline:none;
  :hover {
    background-color: ${colors.blueLight};
  }
`;

Maybe it is possible to extend the button (how?) or does it make more sense to add different components for each button? For my typography i have use "extend". That works. How would that be for the different button versions? Is there a similar way?

export const H1 = styled.h1`
  font-size: 30px;
  color: red;
`
export const H2 = H1.withComponent('h2').extend`
  font-size: 24px;
`

Solution

  • It was working as i added a new component. I imported the PrimaryButton into the new defined component called "Version2".

    import PrimaryButton from './primary';
    

    From here i updated the PrimaryButton like this:

    const Version2 = PrimaryButton.extend`background-color: red;`
    

    This has the advantage that we have a master component for a button. Now we are able to extend the master with diversity of additional styles. In my case background-color.

    With the help of

    export default Version2;
    

    we are now able to add this button called "Version2" into our render function like:

    <PrimaryButton>ClickMe!</PrimaryButton>
    <Version2>ClickMe!</Version2>
    

    and now we get the different buttons. And it´s very modular and clean as well.