https://github.com/atticoos/render-if
⚛ Lightweight React control flow rendering
https://github.com/atticoos/render-if
javascript react react-native
Last synced: 7 months ago
JSON representation
⚛ Lightweight React control flow rendering
- Host: GitHub
- URL: https://github.com/atticoos/render-if
- Owner: atticoos
- Created: 2016-02-05T03:24:19.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2017-06-06T00:01:23.000Z (over 8 years ago)
- Last Synced: 2025-06-27T03:23:31.398Z (7 months ago)
- Topics: javascript, react, react-native
- Language: JavaScript
- Homepage: https://atticuswhite.com/blog/render-if-conditionally-render-react-components/
- Size: 17.6 KB
- Stars: 144
- Watchers: 3
- Forks: 6
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# render-if
[](https://npmjs.org/package/render-if)
[](https://npmjs.org/package/render-if)
[](http://travis-ci.org/ajwhite/render-if)
A tiny, yet conveniently curried way to render conditional React components. Works great with both React and React Native.
```js
renderIf(predicate)(element)
```
## Installation
```
npm install render-if --save
```
You can also install the `eslint` plugin, [eslint-plugin-render-if](https://github.com/v-technologies/eslint-plugin-render-if)
## What it looks like
`renderIf` is a curried function that takes a predicate and returns a function accepting an element that will only be returned if the predicate is satisfied.
The function returned by `renderIf` will also accept a parameterless function which will only be invoked if the predicate is satisfied, allowing for lazy evaluation of inner JSX.
```js
renderIf(1 + 1 === 2)(
Hello World!
)
```
### As an in-line expression
```jsx
class MyComponent extends Component {
render() {
return (
{renderIf(1 + 2 === 3)(
The universe is working
)}
);
}
}
```
### As a lazy in-line expression
```jsx
class MyComponent extends Component {
render() {
return (
{renderIf(1 + 2 === 3)(() => (
This is only invoked if the universe is working
))}
);
}
}
```
### As a named function
```jsx
class MyComponent extends Component {
render() {
const ifTheUniverseIsWorking = renderIf(1 + 2 === 3);
return (
{ifTheUniverseIsWorking(
The universe is still wroking
)}
)
}
}
```
### As a composed function
```jsx
const ifEven = number => renderIf(number % 2 === 0);
const ifOdd = number => renderIf(number % 2 !== 0);
class MyComponent extends Component {
render() {
return (
{ifEven(this.props.count)(
{this.props.count} is even
)}
{ifOdd(this.props.count)(
{this.props.count} is odd
)}
);
}
}
```
## What it no longer looks like
```jsx
class MyComponent extends Component {
render() {
var conditionalOutput;
if (1 + 1 === 2) {
conditionalOutput = I am rendered!;
} else {
conditionalOutput = I am not rendered :(;
}
return (
{conditionalOutput}
{1 + 1 === 2 && I am rendered!}
{this.anotherConditionalRender()}
);
}
anotherConditionalRender() {
if (1 + 1 === 2) {
return I am rendered!
}
}
}
```