skip to Main Content

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


  1. Chosen as BEST ANSWER

    One of my co workers came up with the solution:

    const cn='myClass';
    <div className={styles[cn as keyof typeof styles]}>
    

    Works perfectly!


  2. 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:

    const cname = 'myClass';
    <div className={styles[cname]}>
    

    Keep in mind that it’s case-sensitive (it has to be myClass with m, not MyClass with M) and the styles object has to exist (so you need to import it if it’s defined in another file).

    Login or Signup to reply.
  3. Your answer is good enough.

    you can try these alternative also if needed,

    const cname = 'MyClass';
    
    <div className={styles[`${cname}`]}>
    

    we use square brackets ([]) to access the property of the styles object using the dynamic class name stored in the cname variable. This is a common pattern when you need to dynamically set class names in React with CSS modules

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search