In this tutorial we would going to learn about parsing JSON data in react native application using Fetch API networking library. Fetch API is one of the common API’s used by react native developers. So using this API we would retrieve the complete JSON object from MySQL database server. The MySQL database data is convert into JSON fromat using PHP. So let’s get started 🙂
Contents in this project JSON Parsing ListView :
1. Create Database + Table on your online hosting server or local server :
Create a fresh table inside your database named as FruitsNameListTable . The table has two columns id and fruit_name.
2. Insert Records into Table :
Next step is to insert some records into your table for example i am creating table to store different type of fruit names. Below is the screenshot of my table after inserting records.
3. Create PHP file code to retrieve data from MySQL database and convert into JSON.
Now create Two PHP files First one is DBConfig.php and second is FruitsList.php.
DBConfig.php :- This file contains your hosting server configuration like server host name, database name, database username and database password.
FruitsList.php :- This file fetch the MySQL records from table and convert them into JSON than ECHO them on screen, so they can be accessible.
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(); ?> |
Output of JSON after running the URL should look like this :
4. Start a fresh React Native project. If you don’t know how then read my this tutorial.
5. Add AppRegistry , StyleSheet , ActivityIndicator , ListView , Text , View , Alert component in import block.
1 |
import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from 'react-native'; |
6. Create constructor in your class with props and set this.state isLoading: true.
isLoading: true tells us whether our JSON data is loading from server or not so we can hide the Activity indicator.
1 2 3 4 5 6 |
constructor(props) { super(props); this.state = { isLoading: true } } |
7. Create a function to display the JSON listview selected item. The function name is GetItem with fruit_name parameter, than the function name should look this this : GetItem (fruit_name) .
This function is used to show the selected item from ListView in alert message.
1 2 3 4 5 |
GetItem (fruit_name) { Alert.alert(fruit_name); } |
8. Create componentDidMount()Â Â method. This is a inbuilt method.
1 2 3 4 |
componentDidMount() { } |
9. Create Fetch API network request in componentDidMount()Â Â method.
Using Fetch method first we can pass our HTTP URL from which the JSON is coming. Then using response object we have hold the response coming from server. Now fill the JSON object items to ListView rows one by one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php') .then((response) => response.json()) .then((responseJson) => { let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ isLoading: false, dataSource: ds.cloneWithRows(responseJson), }, function() { // In this block you can do something with new state. }); }) .catch((error) => { console.error(error); }); } |
10. Create ListViewItemSeparator  method.
Using this method we would show a simple item separator line between ListView items.
1 2 3 4 5 6 7 8 9 10 11 |
ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } |
11. Inside the render() block put a if condition checking on this.state.isLoading and if the this.state.isLoading is true then show the <ActivityIndicator /> .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( ); } } |
12. Create custom css class named as MainContainer and rowViewContainer just above the AppRegistry.registerComponent line.
MainContainer : is for complete layout screen.
rowViewContainer : is to modify each ListView element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const styles = StyleSheet.create({ MainContainer :{ // Setting up View inside content in Vertically center. justifyContent: 'center', flex:1, margin: 10 }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, } }); |
13. Add View as parent view in render’s return block and Call the MainContainer class into View.
1 2 3 4 5 6 7 8 |
return ( <View style={styles.MainContainer}> </View> ); |
14. Add ListView component in View.
dataSource : Adding the JSON data into ListView.
renderSeparator : Display a border between items using ListViewItemSeparator()Â .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
return ( <View style={styles.MainContainer}> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} renderRow={(rowData) => <Text style={styles.rowViewContainer} onPress={this.GetItem.bind(this, rowData.fruit_name)} >{rowData.fruit_name}</Text>} /> </View> ); |
15. 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 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from 'react-native'; class Myproject extends Component { constructor(props) { super(props); this.state = { isLoading: true } } GetItem (fruit_name) { Alert.alert(fruit_name); } componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php') .then((response) => response.json()) .then((responseJson) => { let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ isLoading: false, dataSource: ds.cloneWithRows(responseJson), }, function() { // In this block you can do something with new state. }); }) .catch((error) => { console.error(error); }); } ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( <View style={styles.MainContainer}> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} renderRow={(rowData) => <Text style={styles.rowViewContainer} onPress={this.GetItem.bind(this, rowData.fruit_name)} >{rowData.fruit_name}</Text>} /> </View> ); } } const styles = StyleSheet.create({ MainContainer :{ // Setting up View inside content in Vertically center. justifyContent: 'center', flex:1, margin: 10 }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, } }); AppRegistry.registerComponent('Myproject', () => Myproject); |
Screenshots:
can we do the same with List->ListItem ?
Please explain your question ?
react native navigation is not working on my project (i am using windows 7 32 bit pc) .I followed steps from reactnavigation.org if you have any solution .Please help
Jithin you need to run command prompt in Administrator mode before start installing the react navigation library.
hi
Hi,
Can we add these items to picker.
Please tell how can we do that if i use Picker instead of listview here.
Please reply ASAP.
Hitesh i will publish a new tutorial regarding to your query on Tomorrow.
thanks for the response.
Have you published the tutorial ?
Hitesh i have posted the JSON Picker tutorial : https://reactnativecode.com/create-picker-spinner-using-dynamic-json-data/ .
How can we achieve pagination in this listview i.e if i have to show oonly 5-10 items per page. ?
Thanks for comment Hitesh , Currently i am working on it and when it will ready i will post Pagination tutorial 🙂 .
ok, Thanks.
Admin, Have you posted the tutorial ?
thank you so much, it completely works for me
Welcome Anne 🙂
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
can you please tell me about this line ?
rowHasChanged is basically called for each data source rows entry each time you change that data source rows, then only the rows that get changed are re-render (when rowHasChanged returned true).
can i use ip address and port in this, like — 192.162.255.111:6356/ .. ?
network request failed? what’s the problem bro?
Antoni code is working fine, check your Database config file, on which platform you are testing this code?
Sir whenever i update database data..In the app the data will be updated or if not how to update the data
Vivek please explain your question more briefly ? what actually you want ?
hello!
How can I change colour of row (listView) if I select it ?
Sorry dilovar, i have not tried yet this .
Truly when someone doesn’t understand afterward its up to other users that they will assist, so here it happens.
JSON Parse error: Unrecognized token ‘<'? How i can fix it?
Haris in database config file put your own server username password and database name then try again.
Invariant Violation: ListView has been removed from React Native. See https://fb.me/nolistview for more information or use
deprecated-react-native-listview
.You can use FlatList now.
Hi admin, I am trying to do something like this, but instead of retrieving data, I want to insert the selected options in a mysql database, I’m using the example given in this tutorial:
https://www.npmjs.com/package/react-native-multiple-select
I want to create a dinamic button, if there is no option selected, the button will not be visible to user, but if the user selects one or more options, the button will apear on the screen, and after pressing the button I want to insert the items selected in a mysql database, I’m new in rect native and I’ve searched in google about this, but I couldn’t find any solution, could you give an idea how to do this?
Thanks.
Hey, for some reason when I run mine I get a fatal error when I go to the page. My code for the ListView is
{rowData}}
/>
Then above in the componentOnMount method I have
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({ dataSource: ds.cloneWithRows([‘hi’, ‘bye’]) })
{rowData}}
/> It cut out part of my code this is the first piece
Connor the listView is deprecated you have to use FlatList instead of this. And one more thing my coding URL is expired so it won’t work with this URL.
https://pastebin.com/Py36KcTY It cut of part of my code again here is the actual first part.