Search
⌘K
    to navigateEnterto select Escto close

    Use Classnames Package while adding conditional classes

    Use Classnames package while adding conditional classes

    In react, when writing conditional classnames instead of using conditional if-else or ternary operator or switch statement we can use classnames package.

    Instead of:

    1var buttonClass;
    2if(this.state.status === "success") {
    3  buttonClass = "btn btn-success";
    4} else if(this.state.status === "warning") {
    5  buttonClass = "btn btn-warning";
    6} else if(this.state.status === "info") {
    7  buttonClass = "btn btn-info"
    8}
    9
    10return <button className={buttonClass}>{this.state.status}</button>;

    It can be written as:

    1var buttonClass = classNames('btn',
    2  { 'btn-success': this.state.status === 'success' },
    3  { 'btn-warning': this.state.status === 'warning' },
    4  { 'btn-info': this.state.status === 'info' }
    5);
    6
    7return <button className={buttonClass}>{this.state.status}</button>;

    classNames is a function which accepts any number of arguments which are either string or object or array of strings/objects.

    If the argument is a string, the string is included. A string argument is same as a truthy key-value pair.

    1classNames('active');  // 'active'
    2// Is short for
    3classNames({ 'active': true });   // 'active'

    If the arguments are an object, only truthy keys are included and falsy keys are ignored.

    1classNames({
    2  'green': true,
    3  'red'  : false,
    4  'large': true,
    5  'small': false
    6});  // 'green large'

    If the arguments are an array of strings/objects, arrays are flattened recursively and only strings and truthy keys are included.

    1var classes = [
    2  'active',
    3  { 'green': true, 'red': false },
    4  'enabled'
    5];
    6
    7classNames('small', classes);   // 'small active green enabled'
    Previous
    Next