Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda