Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define Multiple Styles React

Is it possible to define multiples classes in React just like in CSS?

const useStyles = makeStyles((theme) => ({
  header1,
  header2,
  header3,
  header4: {
    display: 'flex',
    justifyContent: 'center',
  },
}));
like image 374
Joseph Avatar asked May 04 '26 16:05

Joseph


1 Answers

I'm afraid @material-ui/styles library usage does not work that way. Each key in the object you define represents one class name.

So trying to do something like this:

const useStyles = makeStyles((theme) => ({
    'header1, header2, header3, header4': {
        display: 'flex',
        justifyContent: 'center'
    },
}));

Will result in unusable or invalid class names when the code gets compiled to CSS, because the library will try to compile 'header1, header2, header3, header4' into one class, and since the name contains a space character, the result is garbage.

To solve your problem, the closest thing I can come up with is to define the styles object as its own constant, then assign it to the needed keys. You can also override the original object using spread syntax. Something like:

const headerStyles = {
    display: 'flex',
    justifyContent: 'center'
};
const useStyles = makeStyles((theme) => ({
    header1: headerStyles,
    header2: headerStyles,
    header3: headerStyles,
    header4: {
        ...headerStyles,
        color: 'red'
    }
}));

I hope this is a close-enough compromise for you.

like image 79
Ghassen Louhaichi Avatar answered May 06 '26 05:05

Ghassen Louhaichi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!