Matheew
Matheew

Reputation: 355

Can I pass a className as a prop to StyledComponent in ReactJS?

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?

Upvotes: 1

Views: 1479

Answers (2)

MorKadosh
MorKadosh

Reputation: 6006

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.

Upvotes: 2

user0101
user0101

Reputation: 1517

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

const Button = styled.button`
  &.className {
    // some styles
  }

Upvotes: 0

Related Questions