The worm The worm - 26 days ago 6
HTML Question

Using a ternary operator to return HTML

I know how to use a ternary operator like this:

{ this.state.showThanks ? 'Thanks for your response!' : null }


But I would like to render html and then remove that html on click

{ this.state.showThanks ? <input type="submit" className="decisionButtons" id="canDecisionButton" value="I can play" onClick={() => this.canPlay()}/>
<input type="submit" className="decisionButtons" id="cantDecisionButton" value="I cannot play" onClick={() => this.cannotPlay()}/>
: 'Thanks for your response!' }


I tried something like the above but am getting errors so how can I place html inside a ternary in my react render method?

Answer

JSX elements, like what your ternary expression returns when showThanks is true, always need one parent node. You have two inputs - they need a single parent, so enclose them in a div.

{ this.state.showThanks ? 
<div>
    <input type="submit" className="decisionButtons" id="canDecisionButton" value="I can play" onClick={() => this.canPlay()}/>
    <input type="submit" className="decisionButtons" id="cantDecisionButton" value="I cannot play" onClick={() => this.cannotPlay()}/>
</div>
  : 'Thanks for your response!' }