FlatList is the advance version of ListView with more user handy features like it is fully cross platform and dose support both Android and iOS mobile phone devices. It has also an optional horizontal mode which is used to display the FlatList in horizontal mode. So in this tutorial we would going to create a simple FlatList using JSON Parsing Data which is coming straight from our online hosting server android and iOS tutorial. The JSON data is already stored into a MySQL database. So let’s get started 🙂 .
Contents in this project Create FlatList using JSON Parsing Data :
1. Create MySQL database on your local or online hosting server.
2. Inside that MySQL database create a fresh table named as FruitsNameListTable with 2 columns first one is id second is fruit_name . Set id as primary key in MySQL table. Now insert some records inside your MySQL database table like i did in below screenshot.
Create 2 PHP files 1st one is DBConfig.php and 2nd is FruitsList.php.
FruitsList.php : This file would get all the Records from MySQL db table and ECHO (Print) them on screen into JSON data form.
DBConfig.php : This file holds all the important information like Server Host Name, Database Name, Database Password and Database User Name.
Code for DBConfig.php file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php //Define your host here. $HostName = "localhost"; //Define your database name here. $DatabaseName = "id2070055_reactnativedb"; //Define your database username here. $HostUser = "id2070055_reactnativedb_user"; //Define your database password here. $HostPass = "1234567890"; ?> |
Code for FruitsList.php file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php include 'DBConfig.php'; // Create connection $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM FruitsNameListTable"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $tem = $row; $json = json_encode($tem); } } else { echo "No Results Found."; } echo $json; $conn->close(); ?> |
Screenshot of JSON data after uploading and running FruitsList.php file into web browser :
4. Start a fresh React Native project. If you don’t know how then read my this tutorial.
5. Import AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform in import block.
1 2 3 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from 'react-native'; |
6. Create constructor with props parameter. Define a new state variable inside the constructor named as isLoading and set its value as True . This variable is used to show and hide the ActivityIndicator after parsing the JSON data into FlatList.
1 2 3 4 5 6 7 8 9 |
constructor(props) { super(props); this.state = { isLoading: true } } |
7. Create componentDidMount() method after constructor. This is a inbuilt function and automatically called on App start time. Inside the componentDidMount() function define the fetch web API code. The JSON would be parse using fetch API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php') .then((response) => response.json()) .then((responseJson) => { this.setState({ isLoading: false, dataSource: responseJson }, function() { // In this block you can do something with new state. }); }) .catch((error) => { console.error(error); }); } |
8. Create FlatListItemSeparator() function after componentDidMount() function. This function would Create a custom FlatList item divider line between each FlatList item.
1 2 3 4 5 6 7 8 9 10 11 |
FlatListItemSeparator = () => { return ( <View style={{ height: 1, width: "100%", backgroundColor: "#607D8B", }} /> ); } |
9. Create GetFlatListItem() function . This function is used to PRINT the selected FlatList item value using Alert message on app screen.
1 2 3 4 5 |
GetFlatListItem (fruit_name) { Alert.alert(fruit_name); } |
10. Set a if condition inside the render block. Using this if condition we would check the isLoading state’s value and show and hide the ActivityIndicator .
1 2 3 4 5 6 7 8 9 10 11 12 13 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( ) ; } |
11. Now create FlatList component inside the render’s return block inside a Parent View.
data : Set the dataSource created in componentDidMount() method inside the fetch API.
ItemSeparatorComponent : Call the FlatListItemSeparator() function.
renderItem : render the FlatList item using Text component.
onPress : Call the GetFlatListItem function to show the clicked item value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( <View style={styles.MainContainer}> <FlatList data={ this.state.dataSource } ItemSeparatorComponent = {this.FlatListItemSeparator} renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.fruit_name)} > {item.fruit_name} </Text>} keyExtractor={(item, index) => index} /> </View> ); } |
12. Create Custom Style sheet class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, margin: 10, paddingTop: (Platform.OS === 'ios') ? 20 : 0, }, FlatListItemStyle: { padding: 10, fontSize: 18, height: 44, }, }); |
13. Complete source code for index.android.js / index.ios.js file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from 'react-native'; class Project extends Component { constructor(props) { super(props); this.state = { isLoading: true } } componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php') .then((response) => response.json()) .then((responseJson) => { this.setState({ isLoading: false, dataSource: responseJson }, function() { // In this block you can do something with new state. }); }) .catch((error) => { console.error(error); }); } FlatListItemSeparator = () => { return ( <View style={{ height: 1, width: "100%", backgroundColor: "#607D8B", }} /> ); } GetFlatListItem (fruit_name) { Alert.alert(fruit_name); } render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( <View style={styles.MainContainer}> <FlatList data={ this.state.dataSource } ItemSeparatorComponent = {this.FlatListItemSeparator} renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.fruit_name)} > {item.fruit_name} </Text>} keyExtractor={(item, index) => index} /> </View> ); } } const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, margin: 10, paddingTop: (Platform.OS === 'ios') ? 20 : 0, }, FlatListItemStyle: { padding: 10, fontSize: 18, height: 44, }, }); AppRegistry.registerComponent('Project', () => Project); |
Screenshot of Application in iOS mobile phone device :
Screenshot of Application in Android mobile phone device :
how to re-render flatlist item on load after add data item in mysql? and how to use extraData attribute in flatlist?
Sam you can use Swipe Down To Refresh component to load flatlist and i have not used extraData prop in FlatList yet.
Is there any way out to create .PhP files in React native itself…
or we must use text editors only…..
You must use text editors.
Thank you so much for this .. you have no idea how much i needed it. i have one question please, what if i want to fetch the json file from the app directory instead of the web.. the same file you scereenshoted .. it creates an error.
(attempt to invoke string.equals(object) on a null ref)
hey it is possible to fetch data without using listview or flatlist?
like in simple View components?
Thanks – this is really helpful
Welcome Michael 🙂 .
Hello My friend, very much tanks for the tutorial, i have a trouble when run the application, i get the error “Unexpected token < in JSON at position 0". You know how i can fix it.
my dependences
"dependencies": {
"expo": "^35.0.0",
"react": "16.8.3",
"react-dom": "16.8.3",
"react-native": "0.59.10",
"react-native-gesture-handler": "~1.3.0",
"react-native-reanimated": "~1.2.0",
"react-native-screens": "~1.0.0-alpha.23",
"react-native-unimodules": "0.6.0",
"react-native-web": "^0.11.7",
"react-navigation": "^4.0.10",
"react-navigation-stack": "^1.10.3"
Thanks in advance.
Berna.
how to bind one or more field in
renderItem={({item}) => {item.firstname} }
here
and I got a warning in your code failed child context type : invalid child context ‘virtuilizedCell.cellKey’
replace : keyExtractor={(item, index) => index} with
keyExtractor = { (item, index) => index.toString() }
in FlatListItemStyle if u remove the height property, you list doesnt work, this is because u are rendering more than 10 items that is by default support the flatlist
Hi. Thankyou so much for your code. Your code is working perfectly. I’m able to read data from MySQL table and show it in my Expo App. But, whenever i update my MySQL table, mostly, the app doesn’t show text that match my MySQL table. Can you help? Thanks
Natanael did you set the ID as Auto Increment ?