Reputation: 126
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';
Upvotes: 5
Views: 10349
Reputation: 21
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.
Upvotes: 0
Reputation: 84912
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 "});
Upvotes: 5