Styled Components Revisited

Style the Material-UI components.

Styling Material-UI components

In addition to using a theme to set the global default styles and component props, it can be beneficial to do the same thing at a component level. While using a ThemeProvider to wrap a single component in order to change its style and props is possible, nesting themes can be tricky. We run into issues with overriding the outer theme for the application itself unless we provide a merge function to merge the inner theme with the outer theme.

Instead, Material-UI gives us several ways to apply styles to individual components more directly. In addition to using inline styles like we have been, in the chapter on CSS we also used composition to create a new reusable component that had a specific style incorporated into it. If we need to set props of a Material-UI component as opposed to just the CSS style, using composition is the best way to do it.

If we need to set the style of a component, or if we need to use CSS pseudo-classes that we can’t do with inline styling, we can use the Material-UI styled() function to easily create a styled component. To be specific, the styled() function takes a component as an argument, and returns a function that takes a style dictionary to apply to it. This might sound a little more complicated than it actually is, so here’s an example to help clarify it:

Get hands-on with 1200+ tech skills courses.