0

I have a simple button component with actions passed as props. I've decided to style it using Styled-Components.

In my React Application, I have three buttons with different actions and I would like them to have a different color.

Can I write some CSS classes inside StyledComponent and pass as a prop and 'indicator' which class should my component be styled?

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
Matheew
  • 295
  • 3
  • 14

2 Answers2

2

Sure, this is one of the most basic features of styled components.

One way is to create different components:

const MyButton = styled.button`
  font-size: 12px;
  border: 1px solid red;
`;

const FooButton = styled(MyButton)`
  color: red;
`;

const BooButton = styled(MyButton)`
  color: blue;
`;

Another way is to use props:

const MyButton = styled.button`
  font-size: 12px;
  border: 1px solid red;
  color: ${({type}) => type === 'foo' ? 'red' : 'blue'};
`;
...
... 
<MyButton type={'foo'} />

And for your original question, you can do that. But in most cases it's less "styled-components"ish to use classNames that way.

MorKadosh
  • 5,846
  • 3
  • 25
  • 37
0

You can style classes inside inside styled-components like this:

const Button = styled.button`
  &.className {
    // some styles
  }
user0101
  • 1,277
  • 1
  • 9
  • 17