Categories
React-Native

React-Native NativeBase Flatlist Example

In this example, i am showing how to fetch a json file and list it’s contents in Flatlist using NativeBase’s Card.

messages.json

{
  "title": "Messages List",
  "messages": [
    { "id": "1", "title": "My First Message", "body": "This is the first message.", "author": "author1" },
    { "id": "2", "title": "My Second Message", "body": "This is the second message", "author": "author1" }
  ]
}

App.js

import React from 'react';
import { ActivityIndicator, View, FlatList } from 'react-native';
import { Card, CardItem, Text, Body, Icon } from 'native-base';
export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = { isLoading: true, dataSource: null }
  }

  componentDidMount() {
    return fetch('https://dev.temelkuran.ist/messages.json')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson.messages,
        }, function () {
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {

    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      )
    }

    return (
      <FlatList
        data={this.state.dataSource}
        renderItem={({ item }) =>
          <Card>
            <CardItem header>
              <Text><Icon name="paper" /> {item.title}</Text>
            </CardItem>
            <CardItem>
              <Body>
                <Text>{item.body}</Text>
              </Body>
            </CardItem>
            <CardItem footer>
              <Text><Icon name="person" /> {item.author}</Text>
            </CardItem>
          </Card>
        }
        keyExtractor={({ id }, index) => id}
      />
    );
  }
}

This application should look like: