score:151
just leave banner as being undefined and it does not get included.
score:-1
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:
render: ->
<div classname="container">
{
if something
<h2>coffeescript is magic!</h2>
else
<h2>coffeescript sucks!</h2>
}
</div>
score:-1
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.
score:0
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.
render: function () {
return (
<div id="page">
{this.state.banner ? <div id="banner">{this.state.banner}</div> : ''}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
<script src="http://dragon.ak.fbcdn.net/hphotos-ak-xpf1/t39.3284-6/10574688_1565081647062540_1607884640_n.js"></script>
<script src="http://dragon.ak.fbcdn.net/hphotos-ak-xpa1/t39.3284-6/10541015_309770302547476_509859315_n.js"></script>
<script type="text/jsx;harmony=true">void function() { "use strict";
var hello = react.createclass({
render: function() {
return (
<div id="page">
{this.props.banner ? <div id="banner">{this.props.banner}</div> : ''}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
});
var element = <div><hello /><hello banner="banner"/></div>;
react.render(element, document.body);
}()</script>
score:0
i like the explicitness of immediately-invoked function expressions (iife
) and if-else
over render callbacks
and ternary operators
.
render() {
return (
<div id="page">
{(() => (
const { banner } = this.state;
if (banner) {
return (
<div id="banner">{banner}</div>
);
}
// default
return (
<div>???</div>
);
))()}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
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.
function() {
}()
that need to be wrapped inside parens
(function() {
}())
score:0
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.
const conditional = ({ condition, render }) => {
if (condition) {
return render();
}
return null;
};
class app extends react.component {
constructor() {
super();
this.state = { items: null }
}
componentwillmount() {
settimeout(() => { this.setstate({ items: [1,2] }) }, 2000);
}
render() {
return (
<conditional
condition={!!this.state.items}
render={() => (
<div>
{this.state.items.map(value => <p>{value}</p>)}
</div>
)}
/>
)
}
}
score:0
when having to only render something if passed condition is fullfilled, you can use syntax:
{ condition && what_to_render }
the code in this manner would look like this :
render() {
const { banner } = this.state;
return (
<div id="page">
{ banner && <div id="banner">{banner}</div> }
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
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!
score:0
i just use following snippet in react with typescript
export default function reactif(props: {condition: boolean, children: react.reactnode }) {
return props.condition ? <react.fragment>{props.children}</react.fragment> : <react.fragment/>;
}
score:1
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.
score:1
there is also a really clean one line version... { this.props.product.title || "no title" }
ie:
render: function() {
return (
<div classname="title">
{ this.props.product.title || "no title" }
</div>
);
}
score:1
i made https://github.com/ajwhite/render-if recently to safely render elements only if the predicate passes.
{renderif(1 + 1 === 2)(
<span>hello!</span>
)}
or
const ifuniverseisworking = renderif(1 + 1 === 2);
//...
{ifuniverseisworking(
<span>hello!</span>
)}
score:1
you can conditionally include elements using the ternary operator like so:
render: function(){
return <div id="page">
//conditional statement
{this.state.banner ? <div id="banner">{this.state.banner}</div> : null}
<div id="other-content">
blah blah blah...
</div>
</div>
}
score:1
you can use a function and return the component and keep thin the render function
class app extends react.component {
constructor (props) {
super(props);
this._renderappbar = this._renderappbar.bind(this);
}
render () {
return <div>
{_renderappbar()}
<div>content</div>
</div>
}
_renderappbar () {
if (this.state.renderappbar) {
return <appbar />
}
}
}
score:1
here is my approach using es6.
import react, { component } from 'react';
// you should use reactdom.render instad of react.rendercomponent
import reactdom from 'react-dom';
class togglebox extends component {
constructor(props) {
super(props);
this.state = {
// toggle box is closed initially
opened: false,
};
// http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html
this.togglebox = this.togglebox.bind(this);
}
togglebox() {
// check if box is currently opened
const { opened } = this.state;
this.setstate({
// toggle value of `opened`
opened: !opened,
});
}
render() {
const { title, children } = this.props;
const { opened } = this.state;
return (
<div classname="box">
<div classname="boxtitle" onclick={this.togglebox}>
{title}
</div>
{opened && children && (
<div class="boxcontent">
{children}
</div>
)}
</div>
);
}
}
reactdom.render((
<togglebox title="click me">
<div>some content</div>
</togglebox>
), document.getelementbyid('app'));
demo: http://jsfiddle.net/kb3gn/16688/
i'm using code like:
{opened && <someelement />}
that will render someelement
only if opened
is true. it works because of the way how javascript resolve logical conditions:
true && true && 2; // will output 2
true && false && 2; // will output false
true && 'some string'; // will output 'some string'
opened && <someelement />; // will output someelement if `opened` is true, will output false otherwise
as react
will ignore false
, i find it very good way to conditionally render some elements.
score:1
with es6 you can do it with a simple one-liner
const if = ({children, show}) => show ? children : null
"show" is a boolean and you use this class by
<if show={true}> will show </if>
<if show={false}> won't show </div> </if>
score:2
there is another solution, if component for react:
var node = require('react-if-comp');
...
render: function() {
return (
<div id="page">
<node if={this.state.banner}
then={<div id="banner">{this.state.banner}</div>} />
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
score:2
i use a more explicit shortcut: a immediately-invoked function expression (iife):
{(() => {
if (isempty(routine.queries)) {
return <grid devices={devices} routine={routine} configure={() => this.setstate({configured: true})}/>
} else if (this.state.configured) {
return <devicelist devices={devices} routine={routine} configure={() => this.setstate({configured: false})}/>
} else {
return <grid devices={devices} routine={routine} configure={() => this.setstate({configured: true})}/>
}
})()}
score:2
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.
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
score:3
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.
render: function() {
// this will be renered only if showcontent prop is true
var content =
<div>
<p>something here</p>
<p>more here</p>
<p>and more here</p>
</div>;
return (
<div>
<h1>some title</h1>
{this.props.showcontent ? content : null}
</div>
);
}
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
render: function() {
return (
<div>
<h1>some title</h1>
// this will be renered only if showcontent prop is true
{this.props.showcontent &&
<div>
<p>something here</p>
<p>more here</p>
<p>and more here</p>
</div>
}
</div>
);
}
score:9
this component works when you have more than one element inside "if" branch:
var display = react.createclass({
render: function () {
if (!this.props.when) {
return false;
}
return react.dom.div(null, this.props.children);
},
});
usage:
render: function() {
return (
<div>
<display when={this.state.loading}>
loading something...
<div>elem1</div>
<div>elem2</div>
</display>
<display when={!this.state.loading}>
loaded
<div>elem3</div>
<div>elem4</div>
</display>
</div>
);
}
p.s. someone think that these components are not good for code reading. but in my mind, html with javascript is worse
score:11
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.
score:13
the experimental es7 do
syntax makes this easy. if you're using babel, enable the es7.doexpressions
feature then:
render() {
return (
<div id="banner">
{do {
if (this.state.banner) {
this.state.banner;
} else {
"something else";
}
}}
</div>
);
}
see http://wiki.ecmascript.org/doku.php?id=strawman:do_expressions
score:22
&& + code-style + small components
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 ""
.
render: function() {
var person= ...;
var counter= ...;
return (
<div classname="component">
{person && (
<person person={person}/>
)}
{(typeof counter !== 'undefined') && (
<counter value={counter}/>
)}
</div>
);
}
do notation
es7 stage-0 do notation syntax is also very nice and i'll definitively use it when my ide supports it correctly:
const users = ({users}) => (
<div>
{users.map(user =>
<user key={user.id} user={user}/>
)}
</div>
)
const userlist = ({users}) => do {
if (!users) <div>loading</div>
else if (!users.length) <div>empty</div>
else <users users={users}/>
}
more details here: reactjs - creating an "if" component... a good idea?
score:23
simple, create a function.
renderbanner: function() {
if (!this.state.banner) return;
return (
<div id="banner">{this.state.banner}</div>
);
},
render: function () {
return (
<div id="page">
{this.renderbanner()}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
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 banner
into its own component if it gets too large (or re-used in other places).
score:41
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
:
//dangerous
render: function () {
return (
<div id="page">
<if test={this.state.banner}>
<img src={this.state.banner.src} />
</if>
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
another option is to use an inline function (especially useful with else statements):
render: function () {
return (
<div id="page">
{function(){
if (this.state.banner) {
return <div id="banner">{this.state.banner}</div>
}
}.call(this)}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
another option from react issues:
render: function () {
return (
<div id="page">
{ this.state.banner &&
<div id="banner">{this.state.banner}</div>
}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
score:47
you may also write it like
{ this.state.banner && <div>{...}</div> }
if your state.banner
is null
or undefined
, the right side of the condition is skipped.
score:82
personally, i really think the ternary expressions show in (jsx in depth) 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.
<div id="page">
{this.state.banner ? (
<div id="banner">
<div class="another-div">
{this.state.banner}
</div>
</div>
) :
null}
<div id="other-content">
blah blah blah...
</div>
</div>
score:133
what about this. let's define a simple helping if
component.
var if = react.createclass({
render: function() {
if (this.props.test) {
return this.props.children;
}
else {
return false;
}
}
});
and use it this way:
render: function () {
return (
<div id="page">
<if test={this.state.banner}>
<div id="banner">{this.state.banner}</div>
</if>
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
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):
<if test={this.state.banner}>
<div id="banner">{this.state.banner.url}</div>
</if>
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:
render: function () {
return (
<div id="page">
{this.state.banner &&
<div id="banner">{this.state.banner}</div>}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
if you also need the else branch, just use a ternary operator:
{this.state.banner ?
<div id="banner">{this.state.banner}</div> :
<div>there is no banner!</div>
}
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:
<h3>{this.state.banner.title || 'default banner title'}</h3>
Source: stackoverflow.com
Related Query
- How to have conditional elements and keep DRY with Facebook React's JSX?
- It keep ask me to wrap the jsx with enclosing tag and I think I did what i have to and its causing the problem
- How can render JSX elements with conditional statement?
- How do I test an array of JSX elements in jest with react renderer
- Making a JSX syntax for a MockComponent and have it typed with typescript
- How do I hide and show components with useState or conditional rendering in React?
- Understanding how to have multiple pages with React and react-router
- VSCode How do I debug with es6 mocha unit tests and jsx files
- How can I keep my iterable value in loop with React and Redux?
- Is there a way to have a React child component displayed as a string, with indentations, returns, and with jsx syntactic sugar?
- I have a div with a onClick handler and also buttons inside with onClick events. How do I prevent the buttons from firing the div onclick?
- How can I conditionally render elements with React and Firebase via map function?
- How to have JSX validation and highlighting in .js file in VSCode?
- In React.js, how can I loop through an array of jsx elements and add attributes to them
- I have one this.state and i need pass in my componentDidMount with setState, how use bind(this) in setState?
- How to use mixins with Typescript and React JSX (TSX)
- How can I format an excel file with empty rows to have nested arrays and match a JSON object that I need to render?
- How to dynamically create and render JSX elements, defined from this.props with react
- How to wrap JSX elements in a single div when using .map() with React?
- How to compare each elements in an Array and group the ones that have same data (in my case date) ? JavaScript
- How can I make react render the new state modifications after I have updated the state with hooks and context
- How to render jsx in react with condition true and array mapping?
- How to target DOM and change style in react with mapped elements
- How can I set the state and return JSX with the same function
- How to setState with <select> after component has mounted and options have been generated?
- How do I test a method defined within a functional component, that interacts with DOM elements and has no arguments
- How to center a div within a div but keep it responsive and have it stay in the center
- I have a multidimensional object with several layers of nested arrays and I'm trying to map through all of them in one go but not sure how to
- JSX breaks ... Looping over an array with map generating conditional JSX elements
- JSX how to take counter from loop and display with state
More Query from same tag
- React - why I still got same result when I already change the state
- Data always log 0 if log the length when fetch data from firestore
- Global window Actions in Flux pattern
- cannot read property of state of undefined
- How to access state from another function inside React useEffect
- Redux - My reducers doesn't get called by my action
- Header component doesn't get updated after route change
- Deploy dist folder to heroku
- spread operator - for object, not recognizing its objects name
- React + mobx + openlayers 3
- How to split an alphabetic mapped list into multiple <ul> sorted by first letter with React?
- React auto generate state from form name value pairs from event.target
- Create a Material Ui checkbox with textfiled
- How to mock an api for a React stateless functional component?
- Set React ref after component updates
- Native module RNC_AsyncSQLiteDBStorage tried to override AsyncStorageModule
- How to add/restore the value of process.env.REACT_APP_API_URL?
- how to add attribute without actually editing the HTML element in react
- Blur background when dropdown is opened when using bootstrap dropdown and react
- How to use matchPatch with dynamic links on React Router v6
- Only one highcharts using react-grid-layout can resize
- How do we organize the reducer function in Redux that is returning cloned nested state?
- How to implement a rich text editor such as Quill or Draft.js with Next.js?
- Save Old and new state in React
- Formik form template for xml document creation
- How do I import a jquery plugin into my React component? turnjs
- Validation for Rate component ant.design
- React, state, Why the `count` is not defined?
- Docker - "Missing script: "dev"" - But it's there?
- Is there a difference between using window.scrollTo({top: 50}) over window.scrollTo(0, 50)?