Style a React Component with Styled Components

Sara Vieira
InstructorSara Vieira

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

We are going to learn how to add styles to a react component using the styled-components library.

I've done a lesson on how to Style an HTML Element with Styled Components but now it's time to style React Components. We'll be able to wrap a React component in a styled component to extend the style of that component.

To style an HTML Element, you would do styled.{element} but with a component, you would replace the . with a () so it would look like styled({component})

Here, we will style a button from material-ui and adjust his size with css.

Instructor: [0:00] Let me import styled from 'styled-components'. As you can see, I have a button here. This button comes from Material-UI.

[0:12] Let's say I want this to be 100 percent in width. Right now, there is no prop that will do that. Maybe there is, but I want to do it with styled-components.

[0:20] The way that we can do this is that I can say const, and I can emit fullWidthButton, for example. I can say that it equals styled. If you want to style an HTML element, you put a dot. If you want to style the components, you put parentheses. In here, you pass the actual component that you want it styled.

[0:40] In this case, I want to style the button. I want to delete this because this is not necessary. I'll say width 100 percent. Cool. Nothing happens until we actually use it.

[0:55] As you can see, the button is now 100 percent. Also, as you can see, all the props that work in the button from Material-UI still work here.

[1:03] If I remove this, you will see that the button is completely different. Let's put this back. Let's put this back, and now, let's just add something else to be 50 pixels for who knows why. You can also add that. That's how you can style React components with styled-components.