How to add multiple classes to a ReactJS Component

How to add multiple classes to a ReactJS Component

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 each li:

  • My React component is:
    var AccountMainMenu = React.createClass({
    getInitialState: function() {
    return { focused: 0 };
    },

    clicked: function(index) {
    this.setState({ focused: index });
    },

    render: function() {
    var self = this;
    var accountMenuData = [
    {
    name: “My Account”,
    icon: “icon-account”
    },
    {
    name: “Messages”,
    icon: “icon-message”
    },
    {
    name: “Settings”,
    icon: “icon-settings”
    }
    /*{
    name:”Help & Support   (888) 664.6261″,
    listClass:”no-mobile last help-support last”
    }*/
    ];

    return (

      {accountMenuData.map(function(data, index) {
      var activeClass = “”;

      if (self.state.focused == index) {
      activeClass = “active”;
      }

      return (



    • {data.name}
    • );
      })}

    );
    }
    });

    ReactDOM.render(, document.getElementById(“app-container”));

    Solutions/Answers:

    Solution 1:

    I use classnames. For example:

    ...
        var liClasses = classNames({
          'main-class': true,
          'activeClass': self.state.focused === index
        });
    
        return (<li className={liClasses}>{data.name}</li>);
    ...
    

    Solution 2:

    I use ES6 template literals. For example:

    const error = this.state.valid ? '' : 'error'
    const classes = `form-control round-lg ${error}`
    

    And then just render it:

    <input className={classes} />
    

    One-liner version:

    <input className={`form-control round-lg ${this.state.valid ? '' : 'error'}`} />
    

    Solution 3:

    Just use JavaScript.

    <li className={[activeClass, data.klass, "main-class"].join(' ')} />
    

    If you want to add classes based keys and values in an object you can use the following:

    function classNames(classes) {
      return Object.entries(classes)
        .filter(([key, value]) => value)
        .map(([key, value]) => key)
        .join(' ');
    }
    
    const classes = {
      'maybeClass': true,
      'otherClass': true,
      'probablyNotClass': false,
    };
    
    const myClassNames = classNames(classes);
    // Output: "maybeClass otherClass"
    
    <li className={myClassNames} />
    

    Or even simpler:

    const isEnabled = true;
    const isChecked = false;
    
    <li className={[isEnabled && 'enabled', isChecked && 'checked']
      .filter(e => !!e)
      .join(' ')
    } />
    // Output:
    // <li className={'enabled'} />
    

    Solution 4:

    Concat

    No need to be fancy I am using CSS modules and it’s easy

    import style from '/css/style.css';
    
    <div className={style.style1+ ' ' + style.style2} />
    

    This will result in:

    <div class="src-client-css-pages-style1-selectionItem src-client-css-pages-style2">
    

    In other words, both styles

    Conditionals

    It would be easy to use the same idea with if’s

    const class1 = doIHaveSomething ? style.style1 : 'backupClass';
    
    <div className={class1 + ' ' + style.style2} />
    

    Solution 5:

    This can be achieved with ES6 template literals:

    <input className={`class1 ${class2}`}>
    

    Solution 6:

    You can create an element with multiple class names like this:

    <li className="class1 class2 class3">foo</li>
    

    Naturally, you can use a string containing the class names and manipulate this string to update the class names of the element.

    var myClassNammes = 'class1 class2 class3';
    ...
    <li className={myClassNames}>foo</li>
    

    Related:  Prevent safari loading from cache when back button is clicked