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 push
ing 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';
CodePudding user response:
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 "});
CodePudding user response:
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.