monkeyjs monkeyjs - 2 months ago 28
React JSX Question

ReactJS JSX Syntax for If-Else

I have the following jsx code, I am trying to put some code out of the mapping function, but getting errors with the jsx syntax, I want this block displayed only if there is some data..

{this.props.someData ?
<div className="container">
<h3>Heading</h3>
<div className="block1">
<button>one</button>
<buttontwo</button>
</div>
this.props.someData.map((response, index) => {
return (
<div className="Block2">
<div key={index}>
<span>{response.number}</span>
</div>
</div>
</div>
);
}) : ''}

Answer Source

Write it like this:

{this.props.someData ? 
     <div className="container">
          <h3>Heading</h3>
          <div className="block1">
              <button>one</button>
              <buttontwo</button>
          </div>  
          {this.props.someData.map((response, index) => {
              return ( 
                 <div className="Block2">  
                    <div key={index}>
                     <span>{response.number}</span>
                    </div>
                 </div>
              )})
           }
     </div> 
: <div/>}

Mistake you are doing:

To render any js code inside html elements, {} is required, since you are rendering JSX if the condition is true and inside that using map so put map function inside {}, it will work.