Adding Dynamic Classes to Manual Class Names
In the context of Babel's JavaScript-based JSX, you may encounter the need to append a dynamic class to a list of existing classes. Here's how you can achieve this:
Two Primary Approaches:
Traditional JavaScript:
className={'wrapper searchDiv ' + this.state.something}
This method combines regular string concatenation to append the dynamic class name.
String Template Version:
className={`wrapper searchDiv ${this.state.something}`}
Here, backticks are used to create a string template that allows JavaScript expression interpolation.
JSX Specific Considerations:
In JSX, Curly brackets enclose JavaScript code, so anything within them will be executed. However, a caveat arises when combining JSX strings with curly brackets for attributes.
Alternatives:
Alternatively, you can utilize Babel's transform-class-properties plugin to enable class property assignments in the form:
class MyComponent { classes = 'wrapper searchDiv ' + this.state.something; }
The above is the detailed content of How Can I Add Dynamic Classes to Static Class Names in JSX?. For more information, please follow other related articles on the PHP Chinese website!