DEV Community

Nguyen Trong Duc Luong
Nguyen Trong Duc Luong

Posted on


Conditionally rendering in React with ternary operator

This is a common technique when you want to render one out of two components based on a condition (for example when a state or a prop changes). If you have multiple conditions i advise you to use switch.

In the below example, you can change the greeting text by clicking the button which will change the state of buttonClicked.

Link to the live demo

Alt Text

Top comments (2)

peiche profile image

If you have a condition where you want to render something only if a condition is true (or false), you can do this:

{displayComponent &&
  <MyComponent />
Enter fullscreen mode Exit fullscreen mode

Side note on accessibility, it would be helpful if you'd include some relevant alt text on that image. Better yet, display an actual code snippet instead of an image. Cheers!

a_vietnamese_guy profile image
Nguyen Trong Duc Luong

Thank you for your advise

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post