How to pass props to the makeStyles API in React Material UI

#react #material-ui

Last updated on Nov 29, 2020 by Suraj Sharma



In this tutorial, you will learn how you can pass a function component's props to makeStyles API in React Material UI


Consider, you have a function component CustomMessage, whose css color property is pass from the parent component as props.


And, you want to access that color property directly inside makeStyles API.


To achieve that, you can use an arrow function inside the style property instead of a value


The arrow function has access to the props you have passed to useStyles() as an argument


Example


./CustomMessage.jsx

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles({
  root: {
    color: (props) => props.color,
    fontSize: 16
  }
});

const CustomMessage = (props) => {
  const classes = useStyles(props);

  return (
    <Typography className={classes.root}>
      {message}
    </Typography>
  );
};

export default CustomMessage;


./App.jsx

const App = () => {
  return (
    <>
      <CustomMessage color="red" message="error message" />
      <CustomMessage color="green" message="success message" />
    </>
  );
};

export default App;


Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.