Search code examples
javascriptcssreactjsternary-operatorpostcss

Conditionally adding multiple classes in a ternary using React's className attribute with PostCSS


I'm using PostCSS with React and wanted to add a regular class and modifier class based on my component's state. In short I'd like to perform a show/hide toggle based on the presence/absence of a search input query. Unfortunately it appears that using bracket notation is just rendering the class names in a way that they're unrecognizable.

className={ this.state.suggestionsAvailable ? styles['site-search__suggestions'] styles['site-search__suggestions--active'] : styles['site-search__suggestions'] }>

Has anyone encountered this with a workaround?

import React, { Component } from 'react';
import styles from './SiteSearch.css';

class SiteSearch extends Component {
  constructor(props) {
    super(props);

    this.state = {
      suggestions: [],
      suggestionsAvailable: false
    };
  }

  render() {
    return(
      <form>
        ...
        <div className={ this.state.suggestionsAvailable ? styles['site-search__suggestions'] styles['site-search__suggestions--active'] : styles['site-search__suggestions'] }>
         ...
       </div>
      </form>
    );
  }
}

.site-search__suggestions {
  display: none;
  position: absolute;
  margin-top: 5px;
  border: 1px solid #e0e3e5;
  height: 240px;
  width: 100%;
  border-radius: 6px;
  background-color: rgba(255,255,255,0.9);
}

.site-search__suggestions--active {
  display: block;
}

Solution

  • <div className={ this.state.suggestionsAvailable ? styles['site-search__suggestions'] + " " + styles['site-search__suggestions--active'] : styles['site-search__suggestions'] }>
    

    Is what's needed for this to work, the strings have to be concatenated to show up properly.

    @Carl Edwards also had a solution for ES2015 that uses a template literal:

    ${styles['site-search__suggestions']} ${styles['site-search__suggestions--active']}