Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use Material-UI's withStyles Higher-Order Component to Customize Styles in a React App

    Thomas GrecoThomas Greco
    reactReact
    javascriptJavaScript

    In this lesson we explore the withStyles Higher-Order Component. First, we'll walk through the process of connecting our a React component to the withStyles HOC. Once connected, we'll then see how we can access custom styles using the classes prop withStyles gives us access to.

    Material-UI Homepage Material-UI Style API Docs - withStyles HOC

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: First thing we're going to want to do here is import the withStyles function from the material-ui/styles library.

    Now since withStyles is a higher-order component, we need to wrap our Demo component with it. As you see, Demo is the second set of parameters. The first set of parameters is going to be our styles.

    Now that we are aware of this is going to work, let's import our styles by just saying import styles from styles.shared. Now we can pass it into our higher-order component. Our props is now going to give us access to a classes property. Now classes is going to hold all of our style properties, which in our case are named root and button.

    To render our div with our root property values, we'll just pass in props.classes.root to React className prop. All right, now I am just going to uncomment this HOCDemo and add it to our page. Once we reload, we'll see that our box is appearing and we're just one step away from replicating yet another button, not just any button though.

    We're going to use this button import from material-ui. Again, we're going to add a className prop, but this time we're going to target button instead of root. The file structure, I am just going to add "hocs are the pattern for me!"

    If we reload, we'll see our button appears in the bottom. If we click, we get that ripple effect. Additionally, we can add the variant prop and make this a contained button, and see how it responses to that.

    The last thing we'll do here is just target the size prop and give it a value of small. We'll see that our button now appears on one line here.

    One thing to keep in mind is we can actually access classes directly by just restructuring it and then now we'll no longer have the chain props on there. We'll see we get the same result.