Search code examples
javascriptreactjsternary-operatorconditional-rendering

How to conditionally render commas and periods?


I have three items that are to be conditionally rendered, and I want to be able to render commas between them, and a period if its the last thing to be rendered.

{this.state.a&&i++}    
{this.state.b&&i++}  
{this.state.c&&i++}                  
{this.state.a && (i==1?"item a.":"item a,")}
{this.state.b && (i==2?"item b.":"item b,")}
{this.state.c && (i==3?"item c.":"item c,")}

So this obviously doesn't work as its possible for the other items to be the only item when i=1, it's possible for the third item to need a period when i=2, etc etc. It just seems like a lot of conditions to check for, I'm assuming there has to be an easier way to do this?


Solution

  • You can take help of arrays here.

    const newArray = [];
    {this.state.a && newArray.push('item a')};
    {this.state.b && newArray.push('item b')};
    {this.state.c && newArray.push('item c')};
    
    if (newArray.length) {
      console.log(`${newArray.join(',')}.`);
    } else {
      console.log('No items present.');
    }
    

    I hope this works for you.