• Stars
    star
    1,042
  • Rank 44,217 (Top 0.9 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌗 Render React components conditionally

React If

npm npm bundle size Continuous Integration Issues License Contact Contact

Render React components conditionally.

What does this component do

Take a look at the following presentational component, which contains a commonly used pattern for conditional rendering:

const Bar = ({ name, age, drinkingAge }) => (
  <div>
    <Header />
    {age >= drinkingAge ? <span className="ok">Have a beer, {name}!</span> : <span className="not-ok">Sorry, {name}, you are not old enough.</span>}
    <Footer />
  </div>
);

With React-If you can rewrite this into a more readable, expressive format:

const Bar = ({ name, age, drinkingAge }) => (
  <div>
    <Header />
    <If condition={age >= drinkingAge}>
      <Then>
        <span className="ok">Have a beer, {name}!</span>
      </Then>
      <Else>
        <span className="not-ok">Sorry, {name}, you are not old enough.</span>
      </Else>
    </If>
    <Footer />
  </div>
);

Delaying evaluation of children / condition

It is important to note that, because JavaScript is an eagerly evaluated language, children of both the Then and Else component and condition will be evaluated regardless of the value of the condition. Should that be an issue for performance reasons, one can wrap said children / condition in a arrow function, to delay evaluation of the children / condition, as in the following example:

const renderData = (data) => {
  val computed = /* expensive computation */
  return <span>Here is the result: {computed}</span>;
};

const Foo = ({ data }) => (
    <div>
        <If condition={false}>
            <Then>{() =>
              renderData(data)
            }</Then>
            <Else>
              Nothing to see here
            </Else>
        </If>
        <If condition={!props.bears}>
          <Then>
            No bears
          </Then>

          <Else>
            <If condition={() => props.bears.length}>
              Empty bears array
            </If>
            <Else>
              // Display bears
            </Else>
          </Else>
        </If>
    </div>
)

By doing so, renderData will not be called in the 1st example.

And props.bears.length will not be called in the 2nd example.

Installing and usage

NPM:

npm install react-if Or with yarn: yarn add react-if

// ES2015
import { If, Then, Else, When, Unless, Switch, Case, Default } from 'react-if';

// CommonJS:
const { If, Then, Else, When, Unless, Switch, Case, Default } = require('react-if');

Examples

Switch/Case/Default

import React from 'react';
import { Switch, Case, Default } from 'react-if';

const myNumber = 3;

const Example = () => (
  <div>
    <Switch>
      <Case condition={myNumber === 9}>This will be displayed if condition is matched</Case>
      <Case condition={myNumber > 1}>This will be displayed if condition is matched</Case>
      <Default>This will be displayed if no Case have matching condition</Default>
    </Switch>
  </div>
);

Shorthands: When and Unless

import React from 'react';
import { When, Unless } from 'react-if';

const someCondition = false;

const Example = () => (
  <div>
    <When condition={someCondition}>This will only be displayed, if the condition is TRUE</When>
  </div>
);

const AnotherExample = () => (
  <div>
    <Unless condition={someCondition}>This will only be displayed, if the condition is FALSE</Unless>
  </div>
);

Asynchronous condition

import React from 'react';
import { If, Fallback, Then, Else } from 'react-if';

const Example = () => {
  const fetchData = () => {
    // Return promise
  };

  return (
    <div>
      <If condition={fetchData()}>
        <Fallback>Loading data ...</Fallback>
        <Then>
          {(data) => (
            <span>Here is your data: {data}</span>
          )}
        </Then>
        <Else>
          {(error) => (
            <span>Failed to load data because "{error}"</span>
          )}
        </Else>
      </If>
    </div>
  );
});

API

Note: For a fully auto-generated API, see the github pages website

<If />

Property Type Default
condition Boolean/Promise
keepAlive Boolean false

If condition evaluates to true, renders the <Then /> block will be rendered, otherwise renders the <Else /> block. Either block may be omitted.

This component can contain any number of <Then /> or <Else /> blocks, but only the first block of the right type (either Then or Else, depending on the condition) will be rendered.

When passing a Promise to condition, renders the Fallback block while the Promise is pending, the <Then /> block once Promise is resolved, and the <Else /> block when Promise is rejected. The return value of the Promise can be retrieved within the <Then /> and <Else /> blocks; a render function must be child of these blocks.

<Then>{(returnValue, promiseHistory, cancellablePromise) => <span>{returnValue}</span>}</Then>

The parameters of this render function are:

  • returnValue: The return value of the Promise (for the <Then /> block) or the error (for the <Else /> block);
  • promiseHistory: an Array of all the Promises that were ever passed to <If />. It contains cancellablePromise Objects, that have a promise, as well as a cancel method used to cancel the promise;
  • cancellablePromise: the cancellablePromise Object containing the promise that caused the rendering of this <Then />|<Else /> block;

If the keepAlive prop evaluates to false, each rerender of the <If /> component will automatically ignore the previous Promise if it was still pending.

<Then />

Can contain any number of elements inside, which it renders as-is. It can also contain a function. Should not be used outside of an <If /> block. It will only be displayed, if parent If block's condition is true.

<Else />

Can contain any number of elements inside, which it renders as-is. It can also contain a function. Should not be used outside of an <If /> block. It will only be displayed, if parent If block's condition is false.

<Switch />

A container for <Case condition={...}/> and <Default /> blocks. It will render the first matching Case, or the first encountered Default (, or null).

<Case />

Property Type
condition Boolean

If the Case is the first one to have its condition evaluates to true inside the parent <Switch /> it will be the only rendered.

<Default />

If no Case have its condition evaluates to true inside the parent <Switch />, the first Default will be the only one rendered.

<When />

A shorthand for <If condition={...}><Then>...</Then></If>. The same rules apply to the child elements as with using the Then block.

<Unless />

A shorthand for <If condition={...}><Else>...</Else></If>. The same rules apply to the child elements as with using the Else block.

License

React If is released under the MIT license.

Contributors

Please make sure to read the Contributing Guide before making a pull request.

Thank you to all the people who already contributed to react-if!

More Repositories

1

mdash-chrome

⭐️ Lightweight new tab page for Chrome/Firefox, synced with your bookmarks
JavaScript
21
star
2

node-houdini

Node.js bindings for Houdini, a text escaping library by GitHub (ABANDONED)
C
11
star
3

lfc-haskell

🔮 An experiment with the simply typed lambda calculus, recursion schemes, Cofree, and extensible effects
Haskell
7
star
4

oxid-light

Prototype functional programming language with refinement types, powered by Inox
Scala
7
star
5

mental

🚧 Yet Another ML Dialect (WIP)
Haskell
5
star
6

ADAProject

🔬 Project proposal for the Applied Data Analysis course at EPFL
Jupyter Notebook
3
star
7

msc-thesis-report

MSc Thesis: Systems Modelling with Stainless
TeX
3
star
8

dotfiles

👤 ~/.*
Shell
3
star
9

choreo

Choreographic programming in Scala
Scala
3
star
10

him

🖋️ A text editor written in Haskell (WIP)
Haskell
2
star
11

node-flick

GitHub post-receive hooks handler for Node.js (ABANDONED)
JavaScript
2
star
12

romac.me-old

🌍 Personal website
HTML
2
star
13

AstroVim

My AstroVim config
Lua
2
star
14

thebutton.hs

🔘
Haskell
1
star
15

risc0-ibc

Rust
1
star
16

parsatron.js

🚧 A parser combinators library for JavaScript (ABANDONED)
JavaScript
1
star
17

scalajs-free-canvas

🎨 HTML5 Canvas API as a Free monad for Scala.js (WIP)
Scala
1
star
18

Powered

Powered is a TYPO3 extension which adds functionalities to the Extbase MVC framework shipped with TYPO3 since version 4.3 (DEPRECATED)
PHP
1
star
19

Alfred-BitcoinStats

💰 Displays statistics from realtimebitcoin.info in Alfred 2
1
star
20

stripe-ctf-3.0

Stripe CTF 3.0
Java
1
star
21

Romac.tmbundle

TextMate bundle with many snippets and commands for PHP, JavaScript, XHTML, CSS and TYPO3 (ABANDONED)
PHP
1
star
22

rocket-slog-fairing

Fairing that you can attach to your rocket.rs application to enable use of a slog Logger in your handlers. Fork of https://gitlab.com/pwoolcoc/rocket-slog-fairing
Rust
1
star
23

Askull

ASCII -> EOS-SKL
C
1
star
24

TumblrFS

TumblrFS is a MacFUSE file system which allows you to browse a tumblog as if it was a volume on your computer (EXPERIMENTAL)
Objective-C
1
star
25

x86-snippets

Random x86 assembly snippets I wrote while learning the basics.
Assembly
1
star
26

RRoEmbed

RRoEmbed is a PHP 5.3+ library which provides an object-oriented interface to consume oEmbed resources (ABANDONED)
PHP
1
star