Conditional statements not rendering else block

53 views Asked by At

In my child component Joke I have the following conditional rendering code. Most of the jokes in the backing JSON file have both a question and punchline, but one joke has only a punchline. So if there is a question present I want both question and answer displayed, otherwise I want to display the punchline only, and in a crimson color:

function Joke(props) {
    if (props.question) {
    return (
        <div>
            <h3>Question: {props.question}</h3>
            <h3>Answer: {props.punchline}</h3>
            <hr />
        </div>
    )}
    else {
        return (
            <div>
                <h3 style={{color:"crimson"}}>{props.punchline}</h3>
                <hr />
            </div>
        )}
    }

export default Joke

What is actually outputting now is just Question: and whatever the question is and Answer: with Answer being blank for all cases. Is this conditional logic of checking for question correct?

2

There are 2 answers

0
Rohitha On

Try below code

function Joke(props) {
    return (
        <>
            {props?.question ? 
                          (<div>
                             <h3>Question: {props.question}</h3>
                             <h3>Answer: {props.punchline}</h3>
                             <hr />
                          </div>)
                          : (<div>
                               <h3 style={{color:"crimson"}}>{props.punchline}</h3>
                               <hr />
                             </div>)
                        }
            </>
       )
    }
0
Muneeb On

I would rather do it this way.

Apply strict checks and keep the default condition as well in case, none of the conditions is met.

function Joke(props) {
  let content = <div>None of the condition matched!</div>;

  if (props.question && props.punchline) {
    content = (
      <div>
        <h3>Question: {props.question}</h3>
        <h3>Answer: {props.punchline}</h3>
        <hr />
      </div>
    )
  } else if (props.punchline) {
    content = (
      <div>
        <h3>Answer: {props.punchline}</h3>
        <hr />
      </div>
    )
  }

  return content;
}