5

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';
0

2 Answers 2

6

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 "});
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't there a simpler way than cloneElement? If not, this is what I'm looking for.
What you're doing is rarely needed. JSX elements are not really meant to be modified after they're created. Since it's rarely needed, they havn't made a simpler way to do it.
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.

3 Comments

This is not what I'm looking for. I don't want to pass an expression to classList. element should be created before adding class.
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 a html element in its structure.
I'd like to point out that arrays don't have a split method. In any case, since the className attribute takes a space-separated list of class names, did you by aby chance mean classNames.join(' ')?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.