⚛ Lightweight React control flow rendering
Switch branches/tags
Clone or download
Latest commit 3e6d985 May 25, 2017
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.babelrc module exports babel plugin Feb 5, 2016
.gitignore compile and npmignore Feb 5, 2016
.npmignore exclude .babelrc from package Apr 3, 2016
.travis.yml travis Feb 9, 2016
README.md readme typo May 25, 2017
package.json ⬆️ v0.1.1 Apr 3, 2016
renderIf.js add lazy evaluation Feb 8, 2016
test.js added some spy tests for @lukewestby's thunk added in #2 Feb 9, 2016

README.md

render-if

License NPM version Build Status

A tiny, yet conveniently curried way to render conditional React components. Works great with both React and React Native.

renderIf(predicate)(element)

Installation

npm install render-if --save

You can also install the eslint plugin, 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.

renderIf(1 + 1 === 2)(
  <Text>Hello World!</Text>
)

As an in-line expression

class MyComponent extends Component {
  render() {
    return (
      {renderIf(1 + 2 === 3)(
        <span>The universe is working</span>
      )}
    );
  }
}

As a lazy in-line expression

class MyComponent extends Component {
  render() {
    return (
      {renderIf(1 + 2 === 3)(() => (
        <span>This is only invoked if the universe is working</span>
      ))}
    );
  }
}

As a named function

class MyComponent extends Component {
  render() {
    const ifTheUniverseIsWorking = renderIf(1 + 2 === 3);
    return (
      {ifTheUniverseIsWorking(
        <span>The universe is still wroking</span>
      )}
    )
  }
}

As a composed function

const ifEven = number => renderIf(number % 2 === 0);
const ifOdd = number => renderIf(number % 2 !== 0);

class MyComponent extends Component {
  render() {
    return (
      {ifEven(this.props.count)(
        <span>{this.props.count} is even</span>
      )}
      {ifOdd(this.props.count)(
        <span>{this.props.count} is odd</span>
      )}
    );
  }
}

What it no longer looks like

class MyComponent extends Component {
  render() {
    var conditionalOutput;
    if (1 + 1 === 2) {
      conditionalOutput = <span>I am rendered!</span>;
    } else {
      conditionalOutput = <span>I am not rendered :(</span>;
    }
    return (
      <div>
        <!-- this works, but it can get ugly -->
        {conditionalOutput}
        {1 + 1 === 2 && <span>I am rendered!</span>}
        {this.anotherConditionalRender()}
      </div>
    );
  }
  anotherConditionalRender() {
    if (1 + 1 === 2) {
      return <span>I am rendered!</span>
    }
  }
}