How to have two class names share the same style in ReactJS useStyles

Viewed 164

ReactJS useStyles newbie question. In regular CSS I can have two classes share the same style, such as...

.firstDiv, .secondDiv { border: 1px solid red; }

but I'm not clear on how I would do this using ReactJS useStyle.

const useStyles = makeStyles((theme) => ({
    firstDiv: {
       border: "border: 1px solid red"
    },
    secondDiv: {
       border: "border: 1px solid red"
    }
})

I tried firstDiv, secondDiv: { border: "border: 1px solid red" } but doing so just returns a reference error stating firstDiv isn't defined.

Any assistance is greatly appreciated. I'm sure it's a simple syntax issue but all of my searching online only returns examples on how to add two classes to an element, which isn't what I'm looking for. Thanks in advance!

1 Answers

Since makeStyles takes a JavaScript function that returns an object, your question really is: "How to create an object, where two object keys have the same value?"

For that question, you may found the answer: here.

If you want that for instance that two classes share some properties, that is only possible if you extract them:

const sharedProperties = {
   border: "border: 1px solid red",
   color: "red"
};

const useStyles = makeStyles((theme) => ({
    firstDiv: {
       fontSize: 10,
       ...sharedProperties, 
    },
    secondDiv: {
       fontSize: 20,
       ...sharedProperties,
    }
});
Related