Conditionally Render A React Component

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet

In this lesson, we will explore JSX a little further by looking at how to conditionally render JSX with a Javascript ternary operator. We will see how JSX is simply syntax sugar on top of the React API: React.createElement.

Philip Terzic
Philip Terzic
~ 4 years ago

Great video! Heads up, in the transcript the last code snippet has a typo "redner"

Aaron
Aaron
~ 3 years ago

Should probably just use <div>{message ? message : 'No Message'}</div> (DRY)

Kent C. Dodds
Kent C. Doddsinstructor
~ 3 years ago

Aaron, Yep, that would work well too 👍

Emilio Rios
Emilio Rios
~ 3 years ago

Great video! Just one question, why put parentheses wrapping ternary conditions?

{message ? <div>{message}</div> : <div>No message</div> }

This works too but I suppose there is an explanation about being more careful with parentheses wrapping :)

Emilio Rios
Emilio Rios
~ 3 years ago
Kent C. Dodds
Kent C. Doddsinstructor
~ 3 years ago

Hey Emilio! The parentheses is just formatting to make it easier to read/update. It comes by default with prettier. I hope that's helpful. Good luck!

EggHead Solutions
EggHead Solutions
~ 3 years ago

Should probably just use <div>{message ? message : 'No Message'}</div> (DRY)

Why not a simpler version? ;) <div>{message || 'No message'}</div>

Bobby
Bobby
~ 3 years ago

Would using default parameters in a situation like this be considered an OK practice?

For example:

const Message = ({ message = "No Message" }) => <div>{message}</div>;

To render with 'No Message' could be used as either:

<Message /> or <Message message={undefined} />

Kent C. Dodds
Kent C. Doddsinstructor
~ 3 years ago

Yes Bobby, that'd probably be a better component. And Francisco, that'd work as well. This lesson was intended to solidify the understanding that JSX is simply a light abstraction on top of React.createElement and can therefore be used like you would use regular JavaScript.

Sen Lu
Sen Lu
~ 3 years ago

In Transcript, first code block. Script section w/ Babel.js, change "type" to "src".

james
james
~ 2 years ago

In Transcript, first code block, I think you're closing your <script type="text/babel"></script> too early.

shouldn't the closing tag come after the ReactDOM.render() function?