Joseph
Joseph

Reputation: 7755

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',
  },
}));

Upvotes: 3

Views: 78

Answers (2)

M0nst3R
M0nst3R

Reputation: 5283

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.

Upvotes: 1

takethefake
takethefake

Reputation: 805

You're currently defining an object in the makeStyles method. this ain't CSS.

If you prefer CSS syntax over JSS, you can use the jss-plugin-template plugin.

And write something like this:

const useStyles = makeStyles({
  root: `
    .header1,
    .header2,
    .header3,
    .header4 {
      display: flex;
      justifyContent: center;
    }
  `
});

Reference: https://material-ui.com/styles/advanced/#string-templates

Upvotes: 0

Related Questions