Search code examples
reactjstypescriptif-statementconditional-rendering

React conditional rendering with OR operator


Is it possible to write a conditional render with an OR operator in the statement? to avoid double code.

{regions && || regionsWithAnimals && (
  <>
    <h4>Title</h4>
    <div>
      <RegionsMap
        regions={regions || regionsWithAnimals.regions }
      />
    </div>
  </>
)}

Something like this, this is not working of course

EDIT: I could write:

{regions &&  (
  <>
    <h4>Title</h4>
    <div>
      <RegionsMap
        regions={regions }
      />
    </div>
  </>
)}

and below:

{regionsWithAnimals && (
  <>
    <h4>Title</h4>
    <div>
      <RegionsMap
        regions={regionsWithAnimals.regions }
      />
    </div>
  </>
)}

This is what I want to achieve, but I'm calling two times the same component.


Solution

  • Try something like this:

    {(regions || regionsWithAnimals && regionsWithAnimals.regions) && (
      <>
        <h4>Title</h4>
        <div>
          <RegionsMap
            regions={regions || regionsWithAnimals.regions  }
           />
        </div>
      </>
    )}