I am new to ReactJS and JSX and I am having a little problem with the code below.
I am trying to add multiple classes to the className
attribute on eac
I usually use it like this : (in your case)
<li key={index} className={
"component " +
`${activeClass? activeClass: " not-an-active-class "}` +
`${data.class? " " + data.class : " no-data-class "}`
} />
When it comes to JSX and (usually) we have some json... than you loop it ... component.map, plus some conditional to check if json property exists to render class name depending on property value from JSON. In example below component_color and component_dark_shade are properties from component.map()
<div className={
"component " +
`${component_color? component_color: " no-color "}` +
`${component_dark_shade? " " + component_dark_shade : " light "}`
}/>
Output : <div class="component no-color light" ....
Or: <div class="component blue dark" ....
depending on values from map...
That's what I do:
Component:
const Button = ({ className }) => (
<div className={ className }> </div>
);
Calling Component:
<Button className = 'hashButton free anotherClass' />
I am using React 16.6.3 and @Material UI 3.5.1, and is able to use arrays in className like className={[classes.tableCell, classes.capitalize]}
So in your example, the following would be similar.
<li key={index} className={[activeClass, data.class, "main-class"]}></li>
for more classes adding
... className={`${classes.hello} ${classes.hello1}`...
You can use arrays and then join them using space.
<li key={index} className={[activeClass, data.class, "main-class"].join(' ')}></li>
This will result in :
<li key={index} class="activeClass data.class main-class"></li>