How to pass props with styled components with React?

Estimated read time 2 min read

To pass props to styled components in React, you can use the props object within the template literals that define your styles. This allows you to create dynamic and reusable components that can be styled based on their props.

Here’s an example of how to pass props to styled components in React:

import React from 'react';
import styled from 'styled-components';

const StyledButton = styled.button`
  background-color: ${props => props.primary ? 'blue' : 'gray'};
  color: white;
  font-size: 16px;
  border-radius: 4px;
  padding: 8px 16px;
  border: none;
`;

function MyComponent() {
  return (
    <div>
      <StyledButton>Default Button</StyledButton>
      <StyledButton primary>Primary Button</StyledButton>
    </div>
  );
}

export default MyComponent;

In this example, we’re defining a StyledButton component using styled-components. We’re using the template literal syntax to define the styles of the button based on the primary prop. If primary is true, the background color will be blue; otherwise, it will be gray.

To use the StyledButton component in MyComponent, we’re rendering two instances of the button: one with the default style, and one with the primary prop set to true.

When you define a styled component using styled-components, you can use the props object within the template literal syntax to dynamically generate styles based on the props passed to the component. This allows you to create highly dynamic and customizable components that can be used throughout your React app.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply