![](/uploads/1/2/5/5/125503926/214815082.jpeg)
Render component with condition in React
Use JavaScript operators like if or the conditional operator to create elements. Class LoginControl extends React. Inline If-Else with Conditional Operator. How to have conditional elements and keep DRY with Facebook React's JSX? Just to add another option - if you like/tolerate coffee-script you can use coffee-react to write your JSX in which case if/else statements are usable as they are expressions in coffee-script and not statements.
This component turns this
into this
Install
NPM:
Example
API
<If />
Property | Type |
---|---|
condition | Boolean |
tag | String or Function |
any others props | Any Type |
If
condition
evaluates to true
, renders the <Then />
block will be rendered, otherwise renders the <Else />
block. Either block may be omitted.Default,
<If />
and <Then />
and <Else />
will wrap children in div
tag, if you want wrap it in others html tag, you can set property tag
to your tag name, e.g. <If condition={true} tag='footer'>
or <Then tag='h1'>
or <Else tag='a' onClick={this.onClick}>
This component can contain any number of
<Then />
or <Else />
blocks, and you can containe <If />
in the <Then />
or <Else />
blocks.<Then />
If
condition
evaluates to true
, renders it.<Else />
If
condition
evaluates to false
, renders it.License
GPL-3.0
How do I optionally include an element in JSX? Here is an example using a banner that should be in the component if it has been passed in. What I want to avoid is having to duplicate HTML tags in the if statement.
Bergi393k6565 gold badges613613 silver badges938938 bronze badges
Jack AllanJack Allan9,02477 gold badges3232 silver badges4747 bronze badges
27 Answers
Just leave banner as being undefined and it does not get included.
Michal Kordas5,84833 gold badges3434 silver badges6161 bronze badges
Jack AllanJack Allan9,02477 gold badges3232 silver badges4747 bronze badges
What about this. Let's define a simple helping
If
component. And use it this way:
UPDATE: As my answer is getting popular, I feel obligated to warn you about the biggest danger related to this solution. As pointed out in another answer, the code inside the
<If />
component is executed always regardless of whether the condition is true or false. Therefore the following example will fail in case the banner
is null
(note the property access on the second line):You have to be careful when you use it. I suggest reading other answers for alternative (safer) approaches.
UPDATE 2: Looking back, this approach is not only dangerous but also desperately cumbersome. It's a typical example of when a developer (me) tries to transfer patterns and approaches he knows from one area to another but it doesn't really work (in this case other template languages).
If you need a conditional element, do it like this:
If you also need the else branch, just use a ternary operator:
It's way shorter, more elegant and safe. I use it all the time. The only disadvantage is that you cannot do
else if
branching that easily but that is usually not that common.Anyway, this is possible thanks to how logical operators in JavaScript work. The logical operators even allow little tricks like this:
tobiktobik4,34355 gold badges3333 silver badges4646 bronze badges
Personally, I really think the ternary expressions show in http://facebook.github.io/react/tips/if-else-in-JSX.html are the most natural way that conforms with the ReactJs standards.
See the following example. It's a little messy at first sight but works quite well.
Jim G.9,7361717 gold badges8484 silver badges141141 bronze badges
ChiedoChiedo4,32122 gold badges2121 silver badges2020 bronze badges
You may also write it like
If your
Mo.state.banner
is null
or undefined
, the right side of the condition is skipped.14k2929 gold badges111111 silver badges174174 bronze badges
wialywialy
The
If
style component is dangerous because the code block is always executed regardless of the condition. For example, this would cause a null exception if banner
is null
:Another option is to use an inline function (especially useful with else statements):
Another option from react issues:
bendytreebendytree7,60877 gold badges5353 silver badges7979 bronze badges
This simple test syntax + code-style convention + small focused components is for me the most readable option out there. You just need to take special care of falsy values like
false
, 0
or '
.ES7 stage-0 do notation syntax is also very nice and I'll definitively use it when my IDE supports it correctly:
More details here: ReactJs - Creating an 'If' component... a good idea?
Community♦
Sebastien LorberSebastien Lorber55.2k4040 gold badges212212 silver badges340340 bronze badges
Simple, create a function.
This is a pattern I personally follow all the time. Makes code really clean and easy to understand. What's more it allows you to refactor
Wilfred HughesBanner
into its own component if it gets too large (or re-used in other places).17.9k1111 gold badges9898 silver badges139139 bronze badges
Michael YagudaevMichael Yagudaev4,05322 gold badges3737 silver badges4343 bronze badges
The experimental ES7
do
syntax makes this easy. If you're using Babel, enable the es7.doExpressions
feature then:See http://wiki.ecmascript.org/doku.php?id=strawman:do_expressions
balexandbalexand7,78055 gold badges3434 silver badges3333 bronze badges
As already mentioned in the answers, JSX presents you with two options
- Ternary operator
{ this.state.price ? <div>{this.state.price}</div> : null }
- Logical conjunction
{ this.state.price && <div>{this.state.price}</div> }
However, those don't work for
price 0
. JSX will render the false branch in the first case and in case of logical conjunction, nothing will be rendered. If the property may be 0, just use if statements outside of your JSX.
LyubomirLyubomir12.7k33 gold badges3636 silver badges4747 bronze badges
This component works when you have more than one element inside 'if' branch:
Usage:
P.s. someone think that this components are not good for code reading. But in my mind html with javascript is worse
k.makarovk.makarov61011 gold badge99 silver badges2626 bronze badges
Most examples are with one line of 'html' that is rendered conditionally. This seems readable for me when I have multiple lines that needs to be rendered conditionally.
First example is good because instead of
null
we can conditionally render some other content like {this.props.showContent ? content : otherContent}
But if you just need to show/hide content this is even better since Booleans, Null, and Undefined Are Ignored
ivnivn
There is another solution, if component for React:
Gordon FreemanGordon Freeman
I use a more explicit shortcut: A Immediately-Invoked Function Expression (IIFE):
jsdariojsdario2,06633 gold badges2323 silver badges6161 bronze badges
I made https://www.npmjs.com/package/jsx-control-statements to make it a bit easier, basically it allows you to define
<If>
conditionals as tags and then compiles them into ternary ifs so that the code inside the <If>
only gets executed if the condition is true.Alex GilleranAlex Gilleran
There is also a really clean one line version... { this.props.product.title || 'No Title' }
Ie:
max kaplanmax kaplan
I made https://github.com/ajwhite/render-if recently to safely render elements only if the predicate passes.
or
AtticusAtticus4,32077 gold badges2626 silver badges5454 bronze badges
You can conditionally include elements using the ternary operator like so:
mada-gmada-g
You can use a function and return the component and keep thin the render function
pedronalbertpedronalbert1,41933 gold badges88 silver badges1818 bronze badges
Here is my approach using ES6.
Demo: http://jsfiddle.net/kb3gN/16688/
I'm using code like:
That will render
SomeElement
only if opened
is true. It works because of the way how JavaScript resolve logical conditions:As
pie6kpie6kReact
will ignore false
, I find it very good way to conditionally render some elements.6,32933 gold badges5050 silver badges7272 bronze badges
Maybe it helps someone who comes across the question: All the Conditional Renderings in React It's an article about all the different options for conditional rendering in React.
![React If Else React If Else](/uploads/1/2/5/5/125503926/185136019.png)
Key takeaways of when to use which conditional rendering:
** if-else
- is the most basic conditional rendering
- beginner friendly
- use if to opt-out early from a render method by returning null
** ternary operator
- use it over an if-else statement
- it is more concise than if-else
** logical && operator
- use it when one side of the ternary operation would return null
** switch case
- verbose
- can only be inlined with self invoking function
- avoid it, use enums instead
** enums
- perfect to map different states
- perfect to map more than one condition
** multi-level/nested conditional renderings
- avoid them for the sake of readability
- split up components into more lightweight components with their own simple conditional rendering
- use HOCs
** HOCs
- use them to shield away conditional rendering
- components can focus on their main purpose
** external templating components
- avoid them and be comfortable with JSX and JavaScript
4,11055 gold badges4545 silver badges7070 bronze badges
With ES6 you can do it with a simple one-liner
'show' is a boolean and you use this class by
LeonLeon
I don't think this has been mentioned. This is like your own answer but I think it's even simpler. You can always return strings from the expressions and you can nest jsx inside expressions, so this allows for an easy to read inline expression.
Juan MendesJuan Mendes70k2020 gold badges119119 silver badges162162 bronze badges
I like the explicitness of Immediately-Invoked Function Expressions (
IIFE
) and if-else
over render callbacks
and ternary operators
.You just need to get acquainted of the
IIFE
syntax, {expression}
is the usual React syntax, inside it just consider that you're writing a function that is invoking itself.that need to be wrapped inside parens
Gianluca EspositoGianluca Esposito
There is also a technique using render props to conditional render a component. It's benefit is that the render wouldn't evaluate until the condition is met, resulting in no worries for null and undefined values.
Farzad YZFarzad YZ1,68511 gold badge1313 silver badges2424 bronze badges
When having to only render something if passed condition is fullfilled, you can use syntax:
The code in this manner would look like this :
There are, of course, other valid ways to do this, it's all up to preferences and the occassion. You can learn more ways on how to do conditional rendering in React in this article if you're interested!
Nesha ZoricNesha Zoric
Just to add another option - if you like/tolerate coffee-script you can use coffee-react to write your JSX in which case if/else statements are usable as they are expressions in coffee-script and not statements:
HalHal
Just to extend @Jack Allan answer with references to docs.
React basic (Quick Start) documentation suggests
null
in such case. However, Booleans, Null, and Undefined Are Ignored as well, mentioned in Advanced guide.Oleg V.Oleg V.
Not the answer you're looking for? Browse other questions tagged javascriptreactjsreact-jsx or ask your own question.
![](/uploads/1/2/5/5/125503926/214815082.jpeg)