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

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

Awesome Lists containing this project

README

          

# render-if
[![License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://npmjs.org/package/render-if)
[![NPM version](http://img.shields.io/npm/v/render-if.svg?style=flat)](https://npmjs.org/package/render-if)
[![Build Status](http://img.shields.io/travis/ajwhite/render-if.svg?style=flat)](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!
}
}
}
```