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
- Host: GitHub
- URL: https://github.com/atticoos/react-predicate
- Owner: atticoos
- Created: 2017-02-18T21:25:30.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-02-19T20:26:49.000Z (over 9 years ago)
- Last Synced: 2025-09-19T20:07:42.172Z (10 months ago)
- Topics: javascript, react, react-native, reactjs
- Language: JavaScript
- Size: 9.77 KB
- Stars: 5
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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
);
}
}
```