Search code examples
javascriptreactjsconditional-statementsrendering

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??


Solution

  • {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>