Skip to content Skip to sidebar Skip to footer

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 thi

Solution 1:

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


Solution 2:

Single line example

{(this.state.hello) ? <div>Hello</div> : <div>Goodbye</div>}

or

{(this.state.hello) ? <div>Hello</div> : false}

Solution 3:

I often create an explicit function to to this, to avoid clutter in the main render:

var ChildComponent = React.createClass({
  render: function () {
      return (<p>I am the child component</p>)
  }
});

var RootComponent = React.createClass({

  renderChild: function () {
    if (this.props.showChild === 'true') {
      return (<ChildComponent />);  
    }

    return null;
  },

  render: function () {
   return(
      <div>
        { this.renderChild() }
        <p>Hello World!</p>
      </div>
     )
  }
});

Solution 4:

http://reactkungfu.com/2016/11/dynamic-jsx-tags/

For many React developers using JSX it is not clear how to make a dynamic JSX tag. Meaning that instead of hardcoding whether it is input or textarea or div or span (or anything else) we would like to keep it in a variable.


Post a Comment for "Render JSX Element Based On Condition"