Which is a better to write a react component with styled-components?

Viewed 84

Given some buttons to be shared across a website which one of these two methods is best to use:

const ButtonA = styled.button`
  color: 'red'
`

const ButtonB = styled.button`
  color: 'blue'
`

to be used like this

  const Home = () => {
     return <ButtonA>Button A</ButtonA><ButtonB>Button B</ButtonB>;
  }

or

const Button = styled.button`
  
  ${({variant }) => variant === 'A' && `
    color: red;
  `
  ${({variant }) => variant === 'B' && `
    color: blue;
  `
`

to be used like this:

  const Home = () => {
     return <Button variant="A">Button A</Button><Button variant="B">Button B</Button>;
  }

Please give reasons, advantages and disadvantages for using one method over the other.

1 Answers

As always depends on the case. It's usually better to pass variant prop as in your second example. The problem with the first solution is that you have to repeat the same code. Better to do it like this:

const Button = styled.button`
  // basic styles here
`

const ButtonWithDifferentStyles = styled(Button)`
  // additional styles here
`
Related