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

185
Views
How to add a className to an element inside a variable in react?

I want to add some classes to an element dynamically. I know how to do it with html-dom and how to do it with passing a javascript expression to className. But these are not what I want to do. I am wondering if there is a way to add it like pushing that class to an array or concatenating it to a string in that component object.


It is a pseudo-code of what I'm looking for:

const el = <div className='one' />;
// Notice that I'm not using useRef hook.
el.classList.push('two');

// OR:
el.className += ' two';
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Typically, you will do this by calculating the class name before you create the JSX element:

let className = "one";
className += " two";
const el = <div className={className} />

If that's not possible (say, you received this element as a prop from a parent, and so it has a classname of "one" already baked in), then you would need to use cloneElement:

import { cloneElement } from 'react';

const el = <div className='one' />;
const newElement = cloneElement(el, { className: el.props.className + " two "});
about 4 years ago · Juan Pablo Isaza Report

0

You should try having one array variable with your different classes where you can push conditionally the classes your need and in your jsx split the array.

Like this:

const classNames = ['one']
classNames.push('two');

const el = <div className={classNames.split(' ')} />;

Your element isn't a node element where you have a classList property and you can add and remove classes. It is a JSX element. Even if it ressembles an html element in its structure.

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!