DEV Community

Cover image for Style React component with styled-components : Part-2
Shahjada Talukdar
Shahjada Talukdar

Posted on • Updated on

Style React component with styled-components : Part-2

In My Previous post Style React component with styled-components : Part-1 , I wrote how we can start using styled-components and we created one Spinner component with it.

Now we can see, how we can pass props to the styled component named StyledSpinner and change the color/behavior of it.

For this example, I will change the border color by passing prop. So, the styled component will show the color what we pass to it.

Let's use props for the border color.

border: 16px solid ${props => props.color || "red"};
Enter fullscreen mode Exit fullscreen mode

Here, we can see, I changed the border color #f3f3f3; to ${props => props.color || "red"} which means if any prop is passed it will use that, otherwise it will use red by default.
Cool!

The implementation of this Styled component will be like this-

const StyledSpinner = styled.div`
  border: 16px solid ${props => props.color || "red"};
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
`;
Enter fullscreen mode Exit fullscreen mode

Now we can use this StyledSpinner in our React Component and pass prop named color.

<StyledSpinner color="#f3f3f3" />
Enter fullscreen mode Exit fullscreen mode

Now, I want to add another StyledSpinner without passing any color prop and it should use the default red color.

render() {
    return (
      <Fragment>
        <StyledSpinner color="#f3f3f3" />
        <hr />
        <StyledSpinner />
      </Fragment>
    );
  }
Enter fullscreen mode Exit fullscreen mode

Let's see how they look.

Cool, as we expected!

Hope, someone finds this useful.

Cheers!
👋

As I am trying to contribute contents on the Web, you can buy me a coffee for my hours spent on all of these ❤️😊🌸
Buy Me A Coffee

My Blog: https://shahjada.me

Top comments (0)