Jean Pierre
Jean Pierre

Reputation: 321

Show only the existing elements in React

Having a list of booleans like this:

const a = true;
const b = true;
const c = false;
const d = true;

There is a component that has a label and a value. The label will be the name of the list (the same all the time), and the value will be the list of the true elements from above.

Like this:

Label   value a
        value b
        value d

If none of them are true, it should not print anything.

This is the component:

const CustomListItem = ({ label, value }) => {
  return value ? (
    <ListItem>
      <span className="label-bold">{label}</span>
      <span className="tile__body-value">{value}</span>
    </ListItem>
  ) : null;
};

The problem is that I don't know how to print those elements in the list. This is my approach so far:

      {(a ||
        b ||
        c ||
        d) && (
        <CustomListItem
          label={intl.formatMessage({ id: 'myLabel' })}
          value={
            a && <>{intl.formatMessage({ id: 'a' })}<br /><>,
            b && <>{intl.formatMessage({ id: 'b' })}<br /><>,
            c && <>{intl.formatMessage({ id: 'c' })}<br /><>,
            d && <>{intl.formatMessage({ id: 'd' })}<br /><>
          }
        />
      )}

I get the error:

Unexpected token. Did you mean `{'>'}` or `&gt;`?ts(1382)

I am not using Typescript, I'm using React with Javascript. intl.formatMessage is used to translate the value of a,b,c or d into the user's language.

Any idea how to solve this?

UPDATE

I fixed the typo in the closing tag, now it is like this:

    <CustomListItem
      label={intl.formatMessage({ id: 'oligoShippingOptions' })}
      value={
        (a && (
          <>
            {intl.formatMessage({ id: 'a' })}
            <br />
          </>
        ),
        b && (
          <>
            {intl.formatMessage({ id: 'b' })}
            <br />
          </>
        ),
        c && (
          <>
            {intl.formatMessage({ id: 'c' })}
            <br />
          </>
        ),
        d && (
          <>
            {intl.formatMessage({ id: 'd' })}
            <br />
          </>
        )
     }
  />

It only prints the last true value from the list, in this case, d, why aren't all those true values printed?

Upvotes: 2

Views: 67

Answers (1)

jun
jun

Reputation: 51

This may be what you expect!


<CustomListItem
  label={intl.formatMessage({ id: 'oligoShippingOptions' })}
  value={(
    <>
      {a && (
        <>
          {intl.formatMessage({ id: 'a' })}
          <br />
        </>
      )}
      {b && (
        <>
          {intl.formatMessage({ id: 'b' })}
          <br />
        </>
      )}
      {c && (
        <>
          {intl.formatMessage({ id: 'c' })}
          <br />
        </>
      )}
      {d && (
        <>
          {intl.formatMessage({ id: 'd' })}
          <br />
        </>
      )}
    </>
  )}
/>

Upvotes: 1

Related Questions