Style a React Component with Styled Components

Sara Vieira
InstructorSara Vieira
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 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.

egghead
egghead
~ 9 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today