How to Pass Props to React Components Created with styled-Components?

Sometimes, we want to pass props to React components created with styled-components.

In this article, we’ll look at how to pass props to React components created with styled-components.

Pass Props to React Components Created with styled-Components

To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component.

For instance, we write:

import React from "react";
import styled from "@emotion/styled";

const ArrowStyled = styled.div`
  background-color: green;
  width: 24px;
  height: 30px;
  clip-path: polygon(56% 40%, 40% 50%, 55% 63%, 55% 93%, 0% 50%, 56% 9%);
  transform: rotate(${(props) => props.rotates});
`;

const Arrow = ({ rotates }) => {
  return <ArrowStyled rotates={rotates} />;
};

export default function App() {
  return (
    <div>
      <Arrow rotates="90deg" />
    </div>
  );
}

We create the ArrowStyled component with the styled.div tag.

Then string that we pass into the tag has the rotate value set from a prop.

To do this, we pass in a function into the braces to call the function we passed in when we use the component.

The props parameter has the props.

And we return the value of the prop we want to set to set it.

In App, we set the rotates prop to '90deg' to rotate the arrow 90 degrees.

Therefore, we see the rotated arrow on the screen when we render it in App.

Conclusion

To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component.