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

101
Views
How to add javascript variable within className - react js

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} />
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 {...}.

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!