Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
How do you pass dynamic css classes in react?

I have an image where the CSS class on the image needs to be change dynamically. It is passed in dynamically from this object from the key "size":

export const decals = [
  { label: 'Nikola Tesla', img: `/images/decals/tesla.svg`,  size: `decalMed` },
  { label: 'Tattoo Mom Heart', img: `/images/decals/ARF149.svg`, size: `decalSm`} 

Into another component here:

import styles from ./Shirt.module.css';
<img key={decals[decal].label} src={decals[decal].img} alt={decals[decal].label} className={`${styles}.${decals[decal].size}`}/> 

The className= is the issue. I've tried so many different ways to pass this class.

I've captured this (decals[decal].size) into a variable before passing to the image tag. I've tried to use the style tag instead of className and created a variable to hold the class. I've changed around the brackets. I've tried passing it into an outside div.

Nothing seems to work.

I'm wondering if anyone can clue a react newbie in. Thank you!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

if I am not wrong, you trying to dynamically manage classes that are passing through to the image element.To do that, I recommend you to use "classnames" https://www.npmjs.com/package/classnames

With this package, you can control classNames with variables in your component. I will try explain usage with a little example.

Your style file like

.yourParentClass {
    &.decalMedClass {
        // your styles for this class
    }
    &.decalSmClass {
        // your styles for this class
    }
}

your component file like

import Style from '../style.scss';   // Your classes
var classNames = require('classnames/bind');  // classname package
const cx = classNames.bind(Style);

// your code
render() {
    return (
        <img className={
            cx({
                yourParentClass: true,
                decalMedClass: this.state.sizeMed,
                decalSmClass: !this.state.sizeMed,
            })
        }
        />
    );
}

Basically, you telling that which class gonna be active. Please do not stick with my example, there are good examples on the npm page.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!