You can either use a proper String concatenation or if your needs are wide and highly used then I recommend adding a package for this purpose. In this post, we talk about Multiple classes in Material UI.
So let’s add Multiple classes in Material UI with or without usestyles, withstyles, makestyle.
Method #1: Concat classes properly in className property
You can concat your classes with backticks
const classes = usestyles()
className={`${classes.container} ${classes.spacious}`}
Here notice the space between “classes.container” and “classes.spacious”
This above className will transpile like this:
className=”container spacious”
For example,
<div className={`${this.props.classes.container} ${this.props.classes.spacious}`}>
Method #2: Package for advance class concatenation
If you want advanced className concatenation like conditional class concatenation, etc.
There are two npm packages you can use for this purpose.
clsx – A tiny (228B) utility for constructing className strings conditionally.
Serves as a faster & smaller drop-in replacement for the classnames module.
@material-ui/core now depends on clsx, so if you don’t want to increase your bundle size you’ll want to use clsx instead.
Follow the following steps to set up and use clsx in your project.
- Install clsx package
$ npm i clsx
or
$ yarn add clsx
- Import clsx in your project
import clsx from 'clsx';
- Use clex in your package
// Strings (variadic)
clsx('foo', true && 'bar', 'baz');
//=> 'foo bar baz'
// Objects
clsx({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'
// Objects (variadic)
clsx({ foo:true }, { bar:false }, null, { '--foobar':'hello' });
//=> 'foo --foobar'
// Arrays
clsx(['foo', 0, false, 'bar']);
//=> 'foo bar'
// Arrays (variadic)
clsx(['foo'], ['', 0, false, 'bar'], [['baz', [['hello'], 'there']]]);
//=> 'foo bar baz hello there'
// Kitchen sink (with nesting)
clsx('foo', [1 && 'bar', { baz:false, bat:null }, ['hello', ['world']]], 'cya');
//=> 'foo bar hello world cya'
classnames – A simple JavaScript utility for conditionally joining classNames together.
Follow the following steps to set up and use clsx in your project.
- Install clsx package
npm install classnames
Or
bower install classnames
Or
yarn add classnames
- Import clsx in your project
import classnames from ‘classnames';
- Use ‘classnames’ in your project
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
If you still have the problem let me know in the comment below!