Categories
React Answers

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

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *