Languages
[Edit]
EN

JavaScript - combine names (e.g. CSS class names)

10 points
Created by:
Ela-Davey
663

In this short article, we would like to show how using JavaScript, create simple function that combines names omitting empty or falsy values.

Quick solution: 

// ONLINE-RUNNER:browser;

const combineNames = (...names) => {
    let result = '';
    for (let i = 0; i < names.length; ++i) {
        const name = names[i];
        if (name) {
            if (result) {
                result += ' ';
            }
            result += name;
        }
    }
    return result;
};


// Usage example:

console.log(combineNames('button', 'dark', 'inactive'));   // button dark inactive
console.log(combineNames('button', 'dark', 'active'));     // button dark active
console.log(combineNames('button', null, undefined, ''));  // button

 

Motivation

Imagine you want to assign multiple class names to className property omitting undefined one in React application, e.g.

<div className={combineNames(style.button, style.dark, style.acive)}></div>

Let's suppose dark mode style is undefined, so we expect to get finally:

<div className={`${style.button} ${style.acive}`}></div>

 

Alternative titles

  1. JavaScript - combine names (e.g. style class names)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join