sbezludny / react-if

A better if/else construct for your React components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React If npm badge

Render React components conditionally.

This component helps you turn this

render: function() {
    return (
        <div>
            <Header />
            {this.renderBody()}
            </Footer>
        </div>
    );
},

renderBody: function() {
 return (this.props.age >= this.props.drinkingAge)
    ? <span class="ok">Have a beer, {this.props.name}!</span>
    : <span class="not-ok">Sorry {this.props.name } you are not old enough.</span>;
}

into this

render: function() {
    return (
        <div>
            <Header />
            <If condition={ this.props.age >= this.props.drinkingAge }>
                <Then><span class="ok">Have a beer, {this.props.name}!</span></Then>
                <Else><span class="not-ok">Sorry {this.props.name}, you are not old enough.</span></Else>
            </If>
            </Footer>
        </div>
    );
}

Caveats

With this approach to conditional elements, children of either branch will always be evaluated no matter what. This can be an issue eg. if you're testing an object for nullity, and then try to access one of its property inside of the Then branch. See this StackOverflow discussion as well as issue #1 for more informations.

Install

NPM:

npm install react-if

Bower:

bower install react-if

Example

// Browserify:
var If = require('react-if');
var Then = If.Then;
var Else = If.Else;

// Otherwise
var If = ReactIf;
var Then = If.Then;
var Else = Else.Then;

var Beer = React.createClass({
    
    getDefaultProps: function() {
        return {
            drinkingAge: 16 // Yay, Switzerland!
        };
    },
    
    render: function() {
        return (
            <div>
                <If condition={ this.props.age >= this.props.drinkingAge }>
                    <Then>Have a beer, {this.props.name}!</Then>
                    <Else>Sorry {this.props.name}, you are not old enough.</Else>
                </If>
            </div>
        );
    }
        
});

API

<If />

Property Type
condition Boolean

If condition evaluates to true, renders the <Then /> block will be rendered, otherwise renders the <Else /> block.

This component must contain any number of <Then /> or <Else /> blocks. Only the first block of the right type (either Then or Else, depending on the condition) will be rendered.

<Then />

Must contain only a single child, which it renders as-is. Should not be used outside of an <If /> block.

<Else />

Must only contain a single child, which it renders as-is. Should not be used outside of an <If /> block.

License

React If is released under the MIT license.

About

A better if/else construct for your React components