1

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.

1
  • What do you mean by "does not seem to work" ? That looks like valid JSX. What actually happens that makes you think there's a problem? Commented Jan 18, 2017 at 0:42

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.