Conditionally Render A React Component

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
~ 7 years ago

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

Aaron
~ 7 years ago

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

Kent C. Doddsinstructor
~ 7 years ago

Aaron, Yep, that would work well too 👍

Emilio Rios
~ 6 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
~ 6 years ago
Kent C. Doddsinstructor
~ 6 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
~ 6 years ago

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

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

Bobby
~ 6 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. Doddsinstructor
~ 6 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
~ 6 years ago

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

james
~ 5 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?