Home > Enterprise >  Show or Hide a separator based on data
Show or Hide a separator based on data

Time:11-29

I get 3 items from the database to display. I want to either show or hide a separator ( bullet for example) between them based on whether or not there is a value for items.

    <Items
       description={`${item1 ? `${item1} • ` : ''}
                     ${item2 ? `${item2}` : ''}
                     ${item3 ? ` • ${item3}` : ''}`} 
    />

if item1 is blank then no separator between item1 and item2 if item 2 is blank then no separator between item2 and item3 but if item1 is not blank and item3 is not blank, I need a separator and catch any other edge cases. Is there an elegant way of accomplishing this?

CodePudding user response:

If the separator is the same for each item you can do like this:

[item1, item2, item3].filter(i => i).join(' • ')

CodePudding user response:

There isn't much listed in the question so I'm writing this with the assumption that you're receiving the item from an array. I would code something into a function with a switch, example:

const itemSeparator = (item) => {
  switch (item) {
    case "item1":
      return `* ${item}`;
    case "item2":
      return `${item} *`;
    default:
      return `* ${item} *`;
  }
};

In the component example:

const Child = ({ data }) => {
  return <div>{itemSeparator(data)}</div>;
};

full working example:

Edit Invisible Backdrop

  • Related