• This repository has been archived on 29/Aug/2021
  • Stars
    star
    178
  • Rank 214,989 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated almost 9 years ago

Reviews

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

Repository Details

Lisp-Style conditional rendering in react.

react-cond

Usage | Examples | License


logo by Justin Mezzell

Lisp-Style conditional rendering in react.

Travis Coveralls David npm

Make conditional rendering in react simple and expressive. react-cond is implemented as a component, which takes n clauses as its children. Each clause is an array with a condition and a component. The first child-component, where the condition evaluates to true gets rendered in a Cond component. React-cond is designed to work great with FP-libraries like Ramda.

import { Cond, between, eq, T, Clause, Default } from 'react-cond';

<Cond value={angerLevel}>
	{[ eq(0), <span>sleepy</span> ]}
	{[ between(0, 20), <span>calm</span> ]}
	{[ between(20, 40), <span>angry</span> ]}
	{[ between(40, 41), <span>raging</span> ]}
	{[ T, <span>unknown anger level</span> ]}
</Cond>

// or as components

<Cond value={angerLevel}>
	<Clause test={eq(0)}><span>sleepy</span></Clause>
	<Clause test={between(0, 20)}><span>calm</span></Clause>
	<Clause test={between(20, 40)}><span>angry</span></Clause>
	<Clause test={between(40, 41)}><span>raging</span></Clause>
	<Default><span>unknown anger level</span></Default>
</Cond>

Usage

Installation | Importing | The Component `Cond` | Clauses | Helper Functions

Installation

$ npm install --save react-cond

Importing

React-cond exports the component Cond and a function T.

import { Cond, T } from 'react-cond';
// or the old way
var reactCond = require('react-cond');
var Cond = reactCond.Cond;
var T = reactCond.T;

The Component Cond

Cond is a react component, which controls rendering of its child components.

<Cond value={nr}>
  {[ T, <p key="always-true">always rendered</p> ]}
</Cond>

Cond has two props: value and compare.

value is the value which gets passed to each clause. compare is the default compare function for each clause.

Clauses

The Cond component wraps n clauses. A clause has either the following format: {[ condition, <Component /> ]} f.e. {[ x=> x > 0, <Positive /> ]} or is a Clause/Default component.

import { Cond, T } from 'react-cond';
// ...

<Cond value={nr}>
  {[ x => x > 0, <Positive /> ]}
  {[ x => x < 0, <Negative /> ]}
  {[ T, <Zero /> ]} // `T` always evaluates to true. see Helper Functions.
</Cond>

// or with Clause/Default
import { Cond, Clause, Default } from 'react-cond';
// ...

<Cond value={nr}>
  <Clause test={x => x > 0}><Positive /></Clause>
  <Clause test={x => x < 0}><Negative /></Clause>
  <Default><Zero /></Default>
</Cond>

Helper Functions

T | eq | isTrue | isFalse | isUndefined | isNull | not | gt | lt | gte | lte | between | and | or | value

The following helper functions are optional, but allow you to write even more expressive conditions for your clauses.

T

T

Can be used as an otherwise or else clause. It always evaluates to true.

import { Cond, T } from 'react-cond';
// or youe can import T as otherwise.
import { Cond, T as otherwise } from 'react-cond';

<Cond value={'_test_'}>
  {/* ... your clauses ... */}
  {[ T, <h1>otherwise</h1>]}
</Cond>

eq

eq([property:String], value:Any)

Condition to test if the value is equal (===) to a given value.

import { Cond, eq } from 'react-cond';

<Cond value={this.state.nr}>
  {[ eq(42), <h1>nr is 42</h1>]}
</Cond>

isTrue

isTrue([property:String])

Condition to test if the value is true.

import { Cond, isTrue } from 'react-cond';

<Cond value={true}>
  {[ isTrue, <h1>true</h1>]}
</Cond>

isFalse

isFalse([property:String])

Condition to test if the value is false.

import { Cond, isFalse } from 'react-cond';

<Cond value={false}>
  {[ isFalse, <h1>false</h1>]}
</Cond>

isUndefined

isUndefined([property:String])

Condition to test if the value is undefined.

import { Cond, isUndefined } from 'react-cond';

<Cond value={undefined}>
  {[ isUndefined, <h1>undefined</h1>]}
</Cond>

isNull

isNull([property:String])

Condition to test if the value is null.

import { Cond, isNull } from 'react-cond';

<Cond value={null}>
  {[ isNull, <h1>null</h1>]}
</Cond>

not

not(condition:Function)

Inverts a condition. Can be used to test if a value is not equal (!==) to a given value.

import { Cond, eq, not } from 'react-cond';

<Cond value={this.state.nr}>
  {[ not(eq(42)), <h1>nr isn't 42</h1>]}
</Cond>

gt

gt([property:String], value:Any)

Condition to test if the value is greater than (>) a given value.

import { Cond, gt } from 'react-cond';

<Cond value={this.state.nr}>
  {[ gt(42), <h1>nr greater than 42</h1>]}
</Cond>

lt

lt([property:String], value:Any)

Condition to test if the value is lower than (<) a given value.

import { Cond, lt } from 'react-cond';

<Cond value={this.state.nr}>
  {[ lt(42), <h1>nr lower than 42</h1>]}
</Cond>

gte

gte([property:String], value:Any)

Condition to test if the value is greater or equal than (>=) a given value.

import { Cond, gte } from 'react-cond';

<Cond value={this.state.nr}>
  {[ gte(42), <h1>nr greater or equal than 42</h1>]}
</Cond>

lte

lte([property:String], value:Any)

Condition to test if the value is lower or equal than (<=) a given value.

import { Cond, lte } from 'react-cond';

<Cond value={this.state.nr}>
  {[ lte(42), <h1>nr lower or equal than 42</h1>]}
</Cond>

between

between([property:String], start:Any, end:Any)

Condition to test if the value is between two given values.

import { Cond, between } from 'react-cond';

<Cond value={this.state.nr}>
  {[ between(1, 10), <h1>nr between 1 and 10</h1>]}
</Cond>

and

and(condition:Function, condition:Function)

Combine two conditions with a logical and (&&).

import { Cond, and, eq } from 'react-cond';

const startsWith = x => str => str.startsWith(x);
const endsWith = x => str => str.endsWith(x);

<Cond value={str}>
  {[ and(startsWith('-'), endsWith('-')), <h1>string starts and ends with a dash</h1>]}
</Cond>

or

or(condition:Function, condition:Function)

Combine two conditions with a logical or (||).

import { Cond, or, eq } from 'react-cond';

const startsWith = x => str => str.startsWith(x);
const endsWith = x => str => str.endsWith(x);

<Cond value={str}>
  {[ or(startsWith('-'), endsWith('-')), <h1>string starts or ends with a dash</h1>]}
</Cond>

value

value(property:String, condition:Function)

If your conditions depend on multiple values you can pass an object to the value prop and use value to access them.

<Cond value={{ val1:12, val2: 13 }}>
	{[ and(value('val1', eq(11)), value('val2', eq(12))), <h1>unexpected</h1>]}
	{[ and(value('val1', eq(12)), value('val2', eq(13))), <h1>expected</h1>]}
	{[ T, <h1>unexpected</h1>]}
</Cond>

Examples

Ramda | Multiple Values

Ramda

react-cond works great with libraries like Ramda.

import R, { __, T } from 'ramda';

const notEquals = R.compose(R.not, R.equals);
const gt11 = R.gt(__, 11);

<Cond value={10}>
  {[ notEquals(10), <h1>not 10</h1>]}
  {[ gt11, <h1>greater than 11</h1>]}
  {[ T, <h1>otherwise</h1>]}
</Cond>

Multiple Values

This example shows how you can make conditions which depend on more than one value.

import { Cond, eq, T as otherwise } from 'react-cond';

const List = React.createClass({
  // ...
  render() {
    const { items } = this.state;

    return (
      <ul>
        <Cond value={this.state}>
          {[ ({ isLoading }) => isLoading, <Spinner /> ]}
          {[ eq('hasErrors', true), <Error /> ]}
          {ifNoSearchResult}
          {[ otherwise, items ]}
        </Cond>
      </ul>
    );
  }
});

const ifNoSearchResult = [
  ({ noSearchResult, items }) => noSearchResult || items.length <= 0
  , <NotingFound />
];

License

MIT © Christoph Hermann

More Repositories

1

awesome-fp-js

😎 A curated list of awesome functional programming stuff in js
5,975
star
2

awesome-frp-js

A curated list of awesome functional reactive programming stuff in js
286
star
3

material-iterm

💻 Light & dark material theme for iterm2
238
star
4

react-motion-drawer

Drawer built with react-motion
JavaScript
221
star
5

elm-verify-examples

Elm
167
star
6

redux-elm-middleware

Elm middleware for redux
JavaScript
149
star
7

awesome-ama-answers

A curated list of awesome AMA answers
127
star
8

redux-io

FSA-compliant io monad middleware for redux
JavaScript
66
star
9

compose-function

Function composition
JavaScript
57
star
10

redux-future

FSA-compliant future monad middleware for redux
JavaScript
53
star
11

.dotfiles

🏡
Vim Script
50
star
12

babel-plugin-array-includes

Replaces `arr.includes(val)' with `arr.indexOf(val) >= 0`.
JavaScript
44
star
13

react-mini

Create minimalistic react components
JavaScript
37
star
14

elm-verify

Elm
35
star
15

redux-saga-test

Helper for testing redux-saga
JavaScript
27
star
16

gulp-param

Add params to your tasks
JavaScript
26
star
17

elmi-to-json

Haskell
25
star
18

redux-either

FSA-compliant either monad middleware for redux
JavaScript
23
star
19

react-form-hoc

Higher order component for react forms
JavaScript
22
star
20

gh-contributors-table

🙇 Say "arigatō" to your contributors
JavaScript
21
star
21

recompose-examples

WIP Examples with recompose
JavaScript
20
star
22

mergesort

O(n log n)
JavaScript
20
star
23

underscore.string.fp

This is a wrapper for underscore.string to use it as a FP-library or with Ramda/lodash-fp
JavaScript
20
star
24

react-material-card

A material design card for react
JavaScript
18
star
25

elm-online

Subscribe to online/offline events 📶
Elm
12
star
26

haskell-simple-dsl-examples

Simple examples on how to implement a DSL in Haskell.
Haskell
11
star
27

tasty-test-reporter

An ingredient for tasty that prints a summary and outputs junit xml that works with jenkins.
Haskell
11
star
28

elm-interface-to-json

Haskell
9
star
29

inquander

Inquirer for commander. If no arguments and options are passed to your commander app, it runs inquirer.
JavaScript
8
star
30

pm2-interactive-ui

🚥 interactive cli for pm2
JavaScript
7
star
31

partition-all

Clojure's partition-all in js
JavaScript
7
star
32

extjs5-the-missing-components

This package adds missing components to extjs5.
JavaScript
7
star
33

react-mini-this

React components as pure functions with function bind syntax
JavaScript
6
star
34

debug-view

Elm
6
star
35

arityN

Wraps a function with a function of a sertain arity.
JavaScript
5
star
36

nix-test-runner

Test runner for nix expressions
Rust
5
star
37

grulp

:neckbeard: Never have to worry again if the project is using grunt or gulp. Just use grulp
JavaScript
5
star
38

editable

Elm
5
star
39

elm-reflection

Haskell
5
star
40

radioactive-react-example

Simple example with react and radioactive
JavaScript
5
star
41

create-constants

Create constants
JavaScript
5
star
42

bind-it

DEPRECATED: use stoeffel/bind-first and stoeffel/bind-last
JavaScript
4
star
43

ext.promise

promise for extjs
JavaScript
4
star
44

valid-sift

Check if it's a valid sift filter
JavaScript
3
star
45

compare.js

Comparator functions for you favorite sort-algo
JavaScript
3
star
46

reflux-hoc

Higher-order Component for reflux
JavaScript
3
star
47

if-change-then-notify

Notify me if a certain file changes
JavaScript
3
star
48

set-extra

Elm
3
star
49

Tetris

A lill tetris developed using raphaeljs
JavaScript
3
star
50

pretty-diff

Pretty printing a diff of two values
Haskell
3
star
51

elm-game-of-life

Game of Life in Elm
Elm
3
star
52

expand-object-keys

Expand dotty object keys to objects
JavaScript
3
star
53

underscore.string.cli

String manipulations on the commandline
JavaScript
2
star
54

.dots

🏡
Shell
2
star
55

css-longhand-cli

CLI for css-longhand
JavaScript
2
star
56

react-compose

Compose react components
2
star
57

reassemble-string

🏭 Reassemble your strings
JavaScript
2
star
58

burnhub

Burndown chart for github issues
JavaScript
2
star
59

guard-function

💂‍♂️ You shall not pass!
JavaScript
2
star
60

retrieve-arguments

Retrieves the argumentnames of a function
JavaScript
2
star
61

gulp-macros

sweetjs macros for gulp
JavaScript
2
star
62

abclou

PureScript
2
star
63

tmux-tui

TUI to manage tmux sessions 🚧
Haskell
2
star
64

SEPS-GRP1

JavaScript
2
star
65

advent-of-code-2016

my solutions http://adventofcode.com/
Haskell
2
star
66

elm-check-updates

JavaScript
1
star
67

nur-packages

Nix
1
star
68

format-string

Format a string, using values from an object.
JavaScript
1
star
69

haskell-simple-quasi-quoter

code for small demo on how to use QuasiQuoter
Haskell
1
star
70

Aoc2021

Haskell
1
star
71

use-module

angularjs-style DI for nodemodules
JavaScript
1
star
72

resetable

Elm
1
star
73

reverse-arguments

Reverse the arguments passed to a function.
JavaScript
1
star
74

elm-playground

Elm
1
star
75

bn.js.logo

1
star
76

hosts_alias

my first ruby gem
Ruby
1
star
77

i18next-playground

JavaScript
1
star
78

stoeffel.github.io

🏡
CSS
1
star
79

sencha-leaflet

Leaflet component for sencha touch 2
JavaScript
1
star
80

lan-camp

CSS
1
star
81

rest-param

💬 Returns a function with an appended rest param
JavaScript
1
star
82

array-comprehensions

Functional array comprehension
JavaScript
1
star
83

fparser-cli

a cli for bylexus's fparser
JavaScript
1
star
84

underscore.hasInside

Recursivly searching for a property by name
JavaScript
1
star