user12539769
user12539769

Reputation:

How can I render two JSX variables conditionally?

I've got two JSX variables and I need to render them conditionally. These are my variables:

 const example1= (<div className="row">
             <p>TEST1</p>
             </div>);
 const example2= (<div className="row">
             <p>TEST1</p> 
             </div>);

I need to render example1 and then example1 && example2

How can I do it in JSX??

This one works.

{this.state.input === "1" && example1}

This one doesn't work

{this.state.input === "2" && example1 && example2}
{this.state.input === "2" ? (example1 && example2) : null}

Any ideas??

Upvotes: 0

Views: 64

Answers (2)

Ihsan Fajar Ramadhan
Ihsan Fajar Ramadhan

Reputation: 1033

if you want to show both try this

{this.state.input === "2" ? <>{example1}{example2}</> : ""}

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 84957

{this.state.input === "1" && example1}
{this.state.input === "2" && (
  <React.Fragment>
    {example1}
    {example2}
  </React.Fragment>
)}

If you prefer, you can use <> </> as a shorthand for <React.Fragment> </React.Fragment>

Upvotes: 0

Related Questions