1

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?

0

1 Answer 1

5

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!' }
Sign up to request clarification or add additional context in comments.

2 Comments

I propose exchanging the <div> and </div> in the middle section of the ternary expression for React's <Fragment> and </Fragment> respectively. You can include Fragment in the import of React: import React, { Component, Fragment } from "react". It ensures the rendered HTML does not contain nested divs (which can sometimes lead to problems). Just thought I'd put it out there.
does this work for multiple div or a combination of div & br

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.