An open API service indexing awesome lists of open source software.

https://github.com/atticoos/react-predicate

A control-flow library for React
https://github.com/atticoos/react-predicate

javascript react react-native reactjs

Last synced: 4 months ago
JSON representation

A control-flow library for React

Awesome Lists containing this project

README

          

# react-predicate

A control-flow library for React.

This library offers two categories of predicate components: `Condition` and `Switch`.

```js


Foo


Bar


The value was neither foo nor bar

```
```js


Foo


Bar


The value was neither foo nor bar

```

### Condition

`Condition` wraps a set of `If`, `ElseIf`, and `Else` components. Each component has a `condition` property, where the first to evaluate as `true` becomes rendered. If none evaluate to `true`, then `Else` becomes rendered if it exists. Alternatively, `If` can be used on its own when there is no alternative behavior.

#### Condition Example

```js
class Counter extends React.Component {
state = {count: 0};

increment() {
this.setState({count: this.state.count + 1});
}

decrement() {
this.setState({count: this.state.count - 1});
}

render() {
return (


this.decrement()}>Decrement
{this.state.count}
this.increment()}>Increment


);
}
}

function OddOrEven ({count}) {
return (


The number is even


The number is odd


);
}
```

#### If example

In this example we use `If` without a parent `Condition`. When `If` is not wrapped by a `Condition`, the statements are not aware of each other. Unlike `Condition`, if one evaluates to `true`, the other remains unaffected.

```js
class Counter extends React.Component {
state = {count: 0};

increment() {
this.setState({count: this.state.count + 1});
}

decrement() {
this.setState({count: this.state.count - 1});
}

render() {
return (


this.decrement()}>Decrement
{this.state.count}
this.increment()}>Increment

The number is even


The number is still even


The number is odd


);
}
}
```

### Lazy evaluation

In certain scenarios it's important that you conditional content is not rendered unless the predicate passes.
For any of the predicate components, a function can be provided as the child.
```js

{() => }

```

```js
class LazyEvaluation extends React.Component {
state = {person: null};

createModel() {
this.setState({
person: {name: 'Hello World'}
});
}

render() {
return (


this.createModel()}>Create



{() => }


A person does not yet exist



);
}
}
```