chobo2
chobo2

Reputation: 85865

How to do Nested If statements in ReactJs?

I have something like this.

render(){
    if(//loading){
        return ( <div>loading</div>);
    }
    else{
        if(//has results){
            return (
                     this.props.reducer.results.map((result, i) => {
                            return <Result key={'credit-card-result-' + i} >{result}</Result>;
                     })
            );
        }
        else {
            return (
                <div>no results found </div>
            );
        }
    }
}

but this does not seem to work. I also wanted to do an elseif but that also did not work.

Upvotes: 1

Views: 4043

Answers (2)

Eric G
Eric G

Reputation: 2617

I like to use Element Variables and have one return statement. Using this method you can do your conditional logic like this:

render() {
    let returnThis = null;
    if(//loading){
        returnThis = <div>loading</div>;
    if(//has results){
        returnThis = this.props.reducer.results.map((result, i) => {
                        return <Result key={'credit-card-result-' + i} >{result}</Result>;
                 })
        );
    } 
    else {
        returnThis = <div>no results found </div>;
    }

    return (
        <div>
            {returnThis}
        </div>
    );
}

And here is some more info on their conditional rendering: https://facebook.github.io/react/docs/conditional-rendering.html

Upvotes: 1

Sergio Flores
Sergio Flores

Reputation: 5427

Try this

const { Component, PropTypes } =  React;

class Result extends Component {
    render() {
    return (
        <div>
        {this.props.children}
      </div>
    );
  }
}

class MyComponent extends Component {
    render(){
    const reducer = {
            results: ['A', 'B', 'C', 'D', 'E']
        };
    const loading = false;
    const hasResults = true;

        if (loading){
            return ( <div>loading</div>);
        } else {
            if (hasResults) {
                return (
            <div>hey
          {reducer.results.map((result, i) => {
              return <Result key={'credit-card-result-' + i}>{result}</Result>;
          })}
          </div>
        );
            } else {
                return (
                    <div>no results found </div>
                );
            }
        }
    }
}



ReactDOM.render(
  <MyComponent />,
  document.getElementById('root')
);

Upvotes: 0

Related Questions