How to have conditional elements and keep DRY with Facebook React's JSX?

Jack Allan picture Jack Allan · Mar 20, 2014 · Viewed 141.1k times · Source

How do I optionally include an element in JSX? Here is an example using a banner that should be in the component if it has been passed in. What I want to avoid is having to duplicate HTML tags in the if statement.

render: function () {
    var banner;
    if (this.state.banner) {
        banner = <div id="banner">{this.state.banner}</div>;
    } else {
        banner = ?????
    }
    return (
        <div id="page">
            {banner}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

Answer

Jack Allan picture Jack Allan · Mar 20, 2014

Just leave banner as being undefined and it does not get included.