How to make comparison using inside a render function

I am trying to load a component in either two or three using the state I am getting from input. I know how to use the ternary operator inside a render function. He is like this

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

      


But this will only work for two comparisons. If I have ten components and want to load 10 different components with 10 different options. I'll go if. Here is my attempt. I can't save if the conditions are inside {} like I did with the ternary operator, and if I don't keep them inside {} the render loads it as plain 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 check out this http://facebook.github.io/react/tips/if-else-in-JSX.html

+3


source to share


2 answers


Perhaps 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>
          );

      }

});

      

+2


source


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>;

      

+3


source







All Articles