React-Native ActivityIndicator doesn't hide after animation finish

vtisnado picture vtisnado · Jan 25, 2017 · Viewed 11.3k times · Source

I have an ActivityIndicator that shows while fetch is loading and the wheel disappears when componentDidMount is fired, but keeps and empty block space in the layout. I'm guessing how to unmount this component but anything worked for me.

I'm currently working with these versions:

react-native-cli: 2.0.1
react-native: 0.40.0

This is part of the code I'm using:

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  ... // Couple more components here
  ActivityIndicator,
} from 'react-native';

import NewsList from './NewsList';

export default class HomeView extends Component {

  constructor(props) {
     super(props);
     this.state = {
       noticias: [],
       animating: true,
     };
   }

componentDidMount(){
    fetchFunction() // My fetch function here
      .then(data => this.setState({ data:data }))
      this.state.animating = false
  }

render() {

    return (
        <View>
            <NewsList data={data} /> // My custom component

            <ActivityIndicator
            animating={this.state.animating}
            style={[{height: 80}]}
            color="#C00"
            size="large"
            hidesWhenStopped={true}
            />
        </View>
    );

  }
}

PS: I'm not using Redux.

ActivityIndicator with animation working fine The empty space when animating is set to false

Answer

Henrik R picture Henrik R · Jan 25, 2017

I recommend you to read more about JSX on how to show content conditionally https://facebook.github.io/react/docs/jsx-in-depth.html

I would completely remove ActivityIndicator from the DOM when we are not loading anything

import React, { Component } from 'react';
import { View, ActivityIndicator } from 'react-native';

import NewsList from './NewsList';

export default class HomeView extends Component {
  state = {
    data: [],
    isLoading: true,
  }

  componentDidMount() {
    fetchFunction()
      .then(data => this.setState({ data, isLoading: false }))
  }

  render() {
    const {data, isLoading} = this.state;

    return (
      <View>
        <NewsList data={data} />
        {isLoading && (
          <ActivityIndicator
            style={{ height: 80 }}
            color="#C00"
            size="large"
          />
        )}
      </View>
    );
  }
}