Sometimes, we want to use theme and props in React Material UI makeStyles.
In this article, we’ll look at how to use theme and props in React Material UI makeStyles.
How to use theme and props in React Material UI makeStyles?
To use theme and props in React Material UI makeStyles
, we call it with a function that returns the styles.
We can get preset styles of the theme from the theme
parameter.
And we can set the class property to a function that has props
as the parameter and return an object with the style values given the props
.
For instance, we write:
import React from "react";
import { makeStyles } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
mySelector: (props) => ({
display: "block",
width: props.width,
height: props.height,
marginTop: theme.spacing(2),
marginBottom: theme.spacing(2),
backgroundColor: "yellow"
})
}));
const MyComponent = () => {
const styleProps = { width: "100px", height: "100px" };
const classes = useStyles(styleProps);
return <div className={classes.mySelector}>hello world</div>;
};
export default function App() {
return <MyComponent />;
}
We call makeStyles
with a function that returns an object with the mySelector
class.
We set mySelector
to a function that takes the props
parameter and returns a style object.
We set the width
to props.width
, height
to props.height
.
And we set the margins to theme.spacing(2)
.
Then in MyComponent
, we call useStyles
with styleProps
to set the dimensions of the div.
As a result, we should see the div displayed as a square.
Conclusion
To use theme and props in React Material UI makeStyles
, we call it with a function that returns the styles.
We can get preset styles of the theme from the theme
parameter.
And we can set the class property to a function that has props
as the parameter and return an object with the style values given the props
.