Search code examples
htmlreactjsrenderternary

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?


Solution

  • 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!' }