catandmouse
catandmouse

Reputation: 11809

Conditional rendering with && operator within react return statement

How do I structure my return statement in a class component when my condition is using && operator as in:

if (x === null && y === null) 

...then show this html:

<div className="col-12">
    <SomeComponent />
</div>

else show this html:

   <div className="col-6">
        <SomeOtherComponent />
   </div>
   <div className="col-6">
        <SomeOtherComponent />
   </div>

I need this to be inside the return statement because I am wrapping the entire condition in a <main><div className="row></div></main> wrapper as in:

<main>
  <div className="row">
    // show the above mentioned html conditionally
  </div>
</main>

Upvotes: 2

Views: 2127

Answers (3)

aravind_reddy
aravind_reddy

Reputation: 5466

here is how you do it use ternary operator: {condition ? (if condition is true ) : (if condition is false)}

    <main>
      <div className="row">
          {x === null && y === null ? (
<div className="col-12">
    <SomeComponent />
</div>):  (<div className="col-6">
        <SomeOtherComponent />
   </div>
   <div className="col-6">
        <SomeOtherComponent />
   </div>)}
     </div>
    </main>

Upvotes: 1

Sebastijan Dumančić
Sebastijan Dumančić

Reputation: 1182

You can use ternary operator:

(x === null && y === null) ? (render if true) : (render this if false)

Also, null is falsy value so you can write (!x && !y).

If you want to write with ifs, call method like this.renderComponent() and resolve everything there and just return value or whole component.

Upvotes: 1

kockburn
kockburn

Reputation: 17606

You should use the short hand if statement <condition> ? <if true> : <if false>. Your return statement should look like this.

 return (
    <main>
      {x === null && y === null ? (
        <div className="row">
          <div className="col-12">
            <SomeComponent />
          </div>
        </div>
      ) : (
        <div className="row">
          <div className="col-6">
            <SomeOtherComponent />
          </div>
          <div className="col-6">
            <SomeOtherComponent />
          </div>
        </div>
      )}
    </main>
  );

codesandbox with working example

Upvotes: 2

Related Questions