React conditional rendering
displaying content based on different situations
We have looked into how to display content in the most basic way with React. Now, we can have a look at how to display content based on some condition. This gives our components a more dynamic life, altering content depending on different situations!
At least three methods exist for conditional rendering:
if
statementsternary operator
logical and (&&) operators
Using if
statements
if
statementsThe if
would appear before the final return
statement, with a return
statement of its own, e.g.
In that example, based on someCondition
, the component X
will render
RenderThis
ifsomeCondition
is trueRenderThat
ifsomeCondition
is false
As we know with the return
statement, once executed, the code will skip (i.e. ignore) everything else in the block.
Using ternary operators
This involves the ternary operator syntax that we just have to see with an example:
As we see there, this provides a streamlined syntax compared to the if
statement!
Using logical `&&`
Finally, another way to render conditionally on React:
A little less streamlined than the ternary operator, this method actually works best if we only want to render something for one and only one condition!
Last updated