viciousP
viciousP

Reputation: 520

What is the proper way to concatenate strings with JavaScript (JSX) template literals when one is after comma

I have two strings which I want to concatenate using template literals. Second one is optional and I want to put it after comma (if exist). I know I can do something like this (but it doesn't look proper to me):

<div>
  {a}
  {b ? `, ${b}` : ''}
</div>

Upvotes: 2

Views: 289

Answers (1)

Sasha
Sasha

Reputation: 5944

You can incapsulate logic to filter empty and joining into the component member (or util function), i.e.:

const concatNotEmptyBy = (separator) 
   => (...args) 
   => args
        .filter(n => n) // filter empty
        .join(separator);

and next call it in your component:

<div>
  {concatNotEmptyBy(', ')(a, b)}
</div>

however, if it's only 1 place and only 2 variables then your original way is totally ok.

Upvotes: 3

Related Questions