Praneet Rohida
Praneet Rohida

Reputation: 378

Best way to use conditional rendering in React Native

I am working on a React Native application. In the app, when the user signs in, an API call is made to the server to fetch the data using redux-saga. In the redux store, I am maintaining a boolean variable "fetchingData". It is set to 'true' once the API call is started and set to 'false' once the data is fetched or some error occurs. Now, I want to display a spinner when the data is being fetched, and a FlatList when the data is fetched. I know that I can do this by wrapping the return statement into an if-else condition. I suppose there must be some better way to do this. If someone can help me with this, please tell me a good way to achieve this conditional rendering in React Native. Thank you in advance.

Upvotes: 2

Views: 1423

Answers (2)

Sean Vieira
Sean Vieira

Reputation: 159955

If this is a pattern you use everywhere there are several ways to abstract the pattern out:

  1. Creating a generic <Loading /> component:

    class Loading extends React.Component {
      static defaultProps = {
        waitingElement: <Spinner />,
        renderedElement: null
      };
    
      render() {
        return this.props.loading ? this.props.waitingElement : this.props.renderedElement;
      }
    }
    
    // In some other component's `render`:        
    <Loading renderedElement={<component with=props />}, loading={this.state.isWaiting} />
    
  2. Use a higher-order component to wrap your components:

    function withLoading(Component, spinner = <Spinner />) {
      return class extends Component {
        render() {
          if (this.props.loading) return spinner;
          return super.render();
        }
      };
    }
    
    // Some other file completely
    export default withLoading(class MyComponent {
      render() {
        return "Happy path only!";
      }
    });
    

Upvotes: 2

skynet
skynet

Reputation: 726

I don't think so. When the render() method gets called, appropriate component needs to be the returned based on the state.

render() {
    const isLoading = this.state.isLoading
    return isLoading ?
        <Spinner /> //return a spinner
        :
        <FlatList /> return a list with data
}

Upvotes: 1

Related Questions