0

I'm using CSS Modules in my React app. There is a need to set a class that will consist of 2 strings and then converted to module.

Example.

import React from 'react';
import css from './ContentMedia.module.css';

const Content = (props) => {
    return (
        <div className={css.container}>
           {props.areas && 
               props.areas.map((area) => {
                   return (
                       <div className={`css.areaGrid${area.grid}`} key={area.id}>
                          ...
                       </div>
                   );
               });
           }
        </div>
    );
};

export default Content;

If I'm setting class as className={css.areaGrid${area.grid}} I receive the wrong result (see the picture below). But I need to receive a predefined css-class .areaGrid12 or .areaGrid6 or .areaGrid4 that should look like i.e. Content_areaGrid12_6yth. How should I fix the JSX to make it work?

enter image description here

3 Answers3

2

I think what you need is the following:

<div className={`${css.areaGrid}${area.grid}`} key={area.id}>
   {/* your implementation */}
</div>

Think about the following:

const css = { areaGrid: 'area' };
const area = { grid: 'else' };

console.log(`${css.areaGrid}${area.grid}`);

Or if you have a list of properties in css variable - obviously the values in your case are different:

const area = { grid: '12' };
const css = {
  areaGrid12: 'twelve',
  areaGrid6: 'six',
  areaGrid4: 'four'
};

const result = `${css[`areaGrid${area.grid}`]}`;

console.log(result);

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

This one is what I was looking for .... Thank you Emile Bergeron!!!

className={css[`areaGrid${area.grid}`]}

0

It works if to do this:

let cssClass = '';

if (area.grid === '12') {
    cssClass = css.areaGrid12;
} else if (area.grid === '6') {
    cssClass = css.areaGrid6;
} else if (area.grid === '4') {
    cssClass = css.areaGrid4;
}

<div className={cssClass}> .....

But this solution IMHO is not very flexible ;)