Using the css-in-js method to add classes to a react component, how do I add multiple components?
Here is the classes variable:
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
spacious: {
padding: 10
},
});
Here is how I used it:
return (
<div className={ this.props.classes.container }>
The above works, but is there a way to add both classes, without using the classNames
npm package? Something like:
<div className={ this.props.classes.container + this.props.classes.spacious}>
classNames
package can also be used as advanced as:You could use clsx. I noticed it used in the MUI buttons examples
First install it:
npm install --save clsx
Then import it in your component file:
import clsx from 'clsx';
Then use the imported function in your component:
<div className={ clsx(classes.container, classes.spacious)}>
As already mentioned, you can use string interpolation
And you can try
classnames
library, https://www.npmjs.com/package/classnamesI think this will solve your problem:
and in react component:
If you want to assign multiple class names to your element, you can use arrays.
So in your code above, if this.props.classes resolves to something like ['container', 'spacious'], i.e. if
you can simply assign it to div as
and result will be
You can add multiple string classes and variable classes or props classes at same time in this way
three classes at same time