How to pass props to React Material UI styles?

Sometimes, we want to pass props to React Material UI styles.

In this article, we’ll look at how to pass props to React Material UI styles.

How to pass props to React Material UI styles?

To pass props to React Material UI styles, we can call the useStyle hook returned by makeStyles with the props object.

In makeStyles, we can set the style properties that takes the props as a parameter and return the value we want.

For instance, we write:

import React from "react";
import { makeStyles } from "@material-ui/core";

const useStyles = makeStyles({
  firstStyle: {
    backgroundColor: (props) => props.backgroundColor
  },
  secondStyle: {
    color: (props) => props.color
  }
});

const MyComponent = ({ children, ...props }) => {
  const { firstStyle, secondStyle } = useStyles(props);
  return <div className={`${firstStyle} ${secondStyle}`}>{children}</div>;
};

export default function App() {
  return (
    <MyComponent color="yellow" backgroundColor="purple">
      hello world
    </MyComponent>
  );
}

We call makeStyles with an object that has some class names as properties.

And we set the properties to objects with style properties set to functions that returns the prop value we want.

Next, we define the MyComponent component that gets the props and pass it into useStyles.

Then we set the className to the classes that are returned from useStyles.

Finally, we render MyComponent with color and backgroundColor to render the colors that we set.

They will end up as values in the object that we pass into makeStyles.

As a result, the box has a purple background and the color of the text is yellow.

Conclusion

To pass props to React Material UI styles, we can call the useStyle hook returned by makeStyles with the props object.

In makeStyles, we can set the style properties that takes the props as a parameter and return the value we want.