Solution

To pass props in styled components, you have to mention attributes in your style tag, then can you use those attributes as a props in your style CSS.

Snippet

In this snippet, we will see how to pass props in styled components and then how can the use style component.

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;

`;

<Button color={"green"} primary>Primary</Button>

Example

In this example, we will create styled components as the button and we will pass a primary flag as a prop in style css and we will do the condition is primary true then we will show the background color as white.

Let’s start coding…

App.js

import styled from 'styled-components';

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;

`;

const Example1 = () => {
  return (
   <div>
    <Button>Normal</Button>
    <Button color={"green"} primary>Primary</Button>
  </div>
  );
};

export default Example1;

Output

add element, array

codesandbox