[SOLVED] Modify class name of react element programmatically – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Kostiantyn

Is there a native way to add a style class name to a react element passed as a property WITHOUT using jQuery or any 3rd-party libraries.
The following example should demonstrate what I’m trying to do. Note, react class names are made up.

class Shelf {
    render() {
        return (
            <div>
                <Books authors={<Authors/>}/>
            </div>
        );
    }
}

class Books {
    this.props.authors.addClass('style-class-name'); <- HERE

    render() {
        return (
            <div>
                {this.props.authors}
            </div>
        );
    }
}



Solution

Potentially need more context, but in this kind of scenario, I would use state to dynamically add/remove a class. A basic example would be:

const App = () => {
  const [dynamicClass, setDynamicClass] = useState("");

  return (
    <div className={`normalClass ${dynamicClass}`}>
      <button onClick={() => setDynamicClass("red")}>Red</button>
      <button onClick={() => setDynamicClass("green")}>Green</button>
      <button onClick={() => setDynamicClass("")}>Reset</button>
    </div>
  );
};

The state changes schedule a re-render, hence you end up with dynamic classes depending on the state. Could also pass the class in as a property, or however you want to inject it into the component.


This Question was asked in StackOverflow by Kostiantyn and Answered by Aaron It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?