I’m trying to set the class of a element in a ReactJS Typescript app. I have a variable with the name of the class, but I can’t get it to resolve correctly. If I hard code the class name with
<div className={styles.myClass}>
then it works: but
const cname='MyClass';
<div className={`styles.${cname}`}>
fails.
I’ve tried various different approaches, with and without backticks, with and without double braces, but I can’t get anything to work. Any ideas/hints/tips?
3
Answers
One of my co workers came up with the solution:
Works perfectly!
styles.myClass
is the identifier of a variable, so it cannot be replaced with a string with dot notation, like you’re trying to do. You can, however, get the field from the object with square bracket notation.So the solution is:
Keep in mind that it’s case-sensitive (it has to be
myClass
withm
, notMyClass
withM
) and thestyles
object has to exist (so you need to import it if it’s defined in another file).Your answer is good enough.
you can try these alternative also if needed,
we use
square brackets ([])
to access the property of the styles object using the dynamic class name stored in thecname
variable. This is a common pattern when you need to dynamically set class names in React with CSS modules