Search code examples
react-nativerenderfetch-apireact-native-flatlist

React Native - Render Error - Nothing was returned from render


For some reason I get an error on React Native app:

App(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

My code is:

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

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      isLoading: true,
      dataSource: [],
    };
  }

  componentDidMount() {
    fetch(
      'https://jsonplaceholder.typicode.com/posts',
    )
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        });
      });
  }

  _renderItem = ({item}) => <Text>{item.title}</Text>

  render() {
    if (this.state.isLoading) {
      <View style={styles.container}>
          <ActivityIndicator size="large" animating />
      </View>;
    } else {
      return (
        <View style={styles.container}>
          <FlatList
            data={this.state.dataSource}
            renderItem={(this._renderItem)}
            keyExtractor = {(item, index) => index}
          />
        </View>
      );
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignContent: 'center',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

I don't know where is the problem.


Solution

  • You need to return it

    render() {
    
     if (this.state.isLoading) {
         retrun ( <View style={styles.container}>
              <ActivityIndicator size="large" animating />
          </View>);
        } else {
          return (
            <View style={styles.container}>
              <FlatList
                data={this.state.dataSource}
                renderItem={(this._renderItem)}
                keyExtractor = {(item, index) => index}
              />
            </View>
          );
        }
      }