How to add multiple class names in React Material UI

Last updated on Jun 8, 2021 by Suraj Sharma



Consider you have created a custom useStyles hook returned from makeStyles, passing a style object to the makeStyles method.


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

const useStyles = makeStyles({
  root: {
    width: 240,
    height: 240
  },
  box: {
    fontSize: 12
    padding: 8,
    border: '1px solid #000'
  },
  error: {
    borderColor: 'red'
  },
  success: {
     borderColor: 'green'
  }
});


Now suppose you want to assign multiple classes to a React material UI component and you’re even considering conditionally applying class names to the component.


import Box from '@material/core/Box'
const MyCustomComponent = () => {
  const classes = useStyles();
  return (
    <Box className={classes.root}>
      This is a Material UI Box Component
    </Box>
  );
}


In this tutorial, you will learn how you can add multiple class names to the Material UI component using clsx library


Use clsx to add multiple classes


We are going to use the clsx npm library to add multiple classes to the component.

import clsx from 'clsx';

Latest version of React material UI already has the clsx included in their library so you don’t have to separately install it.

A simple example to add multiple classes to a React material UI component.

<Box className={clsx(classes.root, classes.box)} />}

Another example to conditionally apply classes to the React material UI component

const [isError, setIsError] = useState(false);

...

<Box className={
  clsx(
    classes.root,
    classes.box,
    {[classes.error]: isError, [classes.success]: !isError}
  )
}/>


Related Solutions


Rate this post


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