0

I'm struggling to understand how I can pass through JS variable into className like:

<img className="pos-1 speed-${Math.floor(Math.random() * 10) + 1}" src={Onion1} />

where {Math.floor(Math.random() * 10) + 1} will set a range number so that I can add classes randomly for speed-1 speed-2 etc.

console.log(`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.`);

<img className=`pos-1 speed-${Math.floor(Math.random() * 10) + 1}.` src={Onion1} />

Can anyone help?

Also tried:

const classes = () => {
    return `pos-${Math.floor(Math.random() * 10) + 1} speed-${Math.floor(Math.random() * 10) + 1}.`;
}

<img className={classes} src={Onion1} />
lky
  • 1,081
  • 3
  • 15
  • 31
  • 1
    Does this answer your question? [How to dynamically add a class to manual class names?](https://stackoverflow.com/questions/36209432/how-to-dynamically-add-a-class-to-manual-class-names) – Stucco Apr 08 '22 at 17:10

1 Answers1

6

Your last attempt is very close, you just forgot to enclose it in {...}:

className={`pos-1 speed-${Math.floor(Math.random() * 10) + 1}`}

Any values passed as attributes/props in React that are not simple string literals need to be enclosed in {...}.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34