gates
gates

Reputation: 4603

How to do the comparison using if inside the render function

I am trying to load a component either Two or Three with the help of the state I obtain from the input. I know how to use the ternary operator inside the render function. It's like this

render: function(){
 return( <div>
         {this.state.in===2?<Two/>: <Three/>}
         </div>
          )}


But this would work only for two comparisons, If I have ten components and wants to load 10 different components on 10 different choices. I have go for if. Here is my try regarding it. I am unable to keep if conditions inside {} like I did with ternary operator and If I don't keep them inside {}, render is loading it as normal text. Here is my code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React</title>
    <script src="https://fb.me/react-0.13.3.js"></script>
    <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/jsx">

     var One = React.createClass({

      getInitialState: function(){
        return {in:2}
      },

      handler: function(eve){

        this.setState({
           in: eve.target.value
        })
      },

      render: function(){
        return(
          <div>
          <input value={this.state.in} onChange={this.handler} />
           if(this.state.in ===2){
              <Two/>
            }
            if(this.state.in ===3){
              <Three />
            }

          </div>
          ) 

      }

     }); 


     var Two = React.createClass({

      render: function(){
        return(<div>
            This is component 2
          </div>)

      }

     });

     var Three = React.createClass({

        render: function(){
          return(<div>This is the third one</div>)

        }


     })


      React.render(<One/>,document.getElementById('example'));

    </script>
  </body>
</html>

ps: For further reading and official docs, take a look at this http://facebook.github.io/react/tips/if-else-in-JSX.html

Upvotes: 3

Views: 883

Answers (2)

Carla Fran&#231;a
Carla Fran&#231;a

Reputation: 631

Maybe something like this:

render: function(){
        //Get all your component names and create an array
        var components = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"];

        return(
          <div>
              <input value={this.state.in} onChange={this.handler} />
              < components[this.state.in - 1] />
            </div>
          );

      }

});

Upvotes: 2

Filip Dupanović
Filip Dupanović

Reputation: 33680

React can deal with an array of nodes. So, try creating an array:

let children = [];

if (cond1) children.push(elem1);
if (cond2) children.push(elem2);
if (cond3) children.push(elem3);

return <div>{children}</div>;

Upvotes: 3

Related Questions