danjonescidtrix danjonescidtrix - 1 month ago 11
React JSX Question

Render JSX element based on condition

So I have a simple component within a web app I have been working on and I was wondering if there is a way I could render an element within this component based on the value of this.props.item.

here is my JSX:

var React = require("react"); var actions = require("../actions/SchoolActions");

module.exports = React.createClass({
deleteSchool: function(e){
e.preventDefault();
actions.deleteSchool(this.props.info);
},
render:function(){
return(
<div className="panel panel-default">
<div className="panel-heading">
{this.props.info.name}
<span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span>
</div>
<div className="panel-body">{this.props.info.tagline}</div>
</div>
)
} })


I wanted to be able to do something like this:

render:function(){
return(
code blah blah...

if (this.props.info = "nothing"){
<div className="panel-body">{this.props.info.tagline}</div>
}

...code blah blah


But I cannot write javascript withing the render function itself. Does anyone know how I could do this? Any help or advice is appreciated, thank you in advance.

Answer

You can use conditionally render using if and return the appropriate jsx

render(){
    if(something){
       return(<MyJsx1/>)
    }else{
       return(<MyJsx2/>)
    }
}

You can chaage your component to:

       render:function(){
            return(
                <div className="panel panel-default">
                    <div className="panel-heading">
                        {this.props.info.name}
                        <span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span>
                    </div>
                   {this.props.info = "nothing"?
                   (<div className="panel-body">{this.props.info.tagline}</div>)
                   :null}

                </div>
            )
        } })

https://facebook.github.io/react/docs/conditional-rendering.html

Comments