This tutorial is the second part of JSON ListView with single Item From MySQL database Tutorial. In this tutorial we would going to create a fresh react native application with JSON data already inserted into MySQL database. This ListView data contain multiple students records which is a multi type data, like id, name, phone number and subject. So we would show – render Multiple Items of JSON data into each ListView item one by one.
What we are doing in this project 🙂Â
- Creating MySQL database with table.
- Insert some students record inside the db.
- Create PHP script to convert MySQL data into JSON data.
- Parse JSON data into React native android and iOS application.
- Set JSON data into ListView.
Contents in this project Create Custom JSON ListView with Multiple Items :
1. Create MySQL database on your hosting server.
2. Create a table inside MySQL database named as Student_Table . Student table holds 4 columns id, student_name, student_phone_number, student_subject.
3. Insert some random students records inside the table. I am inserting my M.C.A classmates name.
4. Create PHP Script to convert the MySQL db data into JSON form :
Now I am creating Two PHP files First one is DBConfig.php and second is StudentsList.php.
DBConfig.php :-Â This file contains your hosting server configuration like server host name, database name, database username and database password.
StudentsList.php :-Â This file fetch the MySQL table records and print them on screen in JSON form.
Code for DBConfig.php :
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 StudentsList.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); } // Creating SQL command to fetch all records from Table. $sql = "SELECT * FROM Student_Table"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $item = $row; $json = json_encode($item); } } else { echo "No Results Found."; } echo $json; $conn->close(); ?> |
Screenshot of JSON data after executing the StudentsList.php file :
5. Start a fresh React Native project. If you don’t know how then read my this tutorial.
6. Import AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert, Platform and TouchableOpacity component in your project.
1 2 3 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert, Platform, TouchableOpacity} from 'react-native'; |
7. Create constructor in project’s class with props and set isLoading variable state true. The isLoading variable is used to control ActivityIndicator show and hide state.
1 2 3 4 5 6 |
constructor(props) { super(props); this.state = { isLoading: true } } |
8. Create function GetItem() to display the selected student name from ListView.
1 2 3 4 5 |
GetItem (student_name) { Alert.alert(student_name); } |
9. Create componentDidMount() method after GetItem function. This is a react native’s inbuilt method.
1 2 3 4 |
componentDidMount() { } |
10. Create react native fetch web API inside the componentDidMount() function. This function would parse the JSON coming from Server using HTTP URL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/StudentsList.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); }); } |
11. Create ListViewItemSeparator function just after the componentDidMount() function. This function is used to show a separator line between each ListView element.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } |
12.  Create render() function after ListViewItemSeparator function, Now put a if condition inside it. Using this if condition we would check the isLoading value and if its true then we show the ActivityIndicator and if its falsethen would hide the ActivityIndicator .
1 2 3 4 5 6 7 8 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } |
13. Create a Parent View inside the default render’s return block.
1 2 3 4 5 6 7 8 9 10 11 |
render() { return ( <View style={styles.MainContainer}> </View> ); } |
14. Create ListView component inside the Parent View.
dataSource : This would set  the JSON parse data into ListView.
renderSeparator : Call the ListViewItemSeparator function to show a separator line between ListView items.
renderRow={(rowData) =>Â : This would used to show component inside the ListView. For example in our case we would show Image component and Text component in ListView.
TouchableOpacity : Call the GetItem() function on the onPress of TouchableOpacity so when user clicks any of the ListView item it would send the Student name with this function on onPress.
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 |
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) => <View style={{flex:1, flexDirection: 'column'}} > <TouchableOpacity onPress={this.GetItem.bind(this, rowData.student_name)} > <Text style={styles.textViewContainer} >{'id = ' + rowData.id}</Text> <Text style={styles.textViewContainer} >{'Name = ' + rowData.student_name}</Text> <Text style={styles.textViewContainer} >{'Phone Number = ' + rowData.student_phone_number}</Text> <Text style={styles.textViewContainer} >{'Subject = ' + rowData.student_subject}</Text> </TouchableOpacity> </View> } /> </View> ); } |
15. Create custom css class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
const styles = StyleSheet.create({ MainContainer :{ // Setting up View inside content in Vertically center. justifyContent: 'center', flex:1, paddingTop: (Platform.OS === 'ios') ? 20 : 0, backgroundColor: '#00BCD4', padding: 5, }, textViewContainer: { textAlignVertical:'center', padding:10, fontSize: 20, color: '#fff', } }); |
16. 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, ActivityIndicator, ListView, Text, View, Alert, Platform, TouchableOpacity} from 'react-native'; class Project extends Component { constructor(props) { super(props); this.state = { isLoading: true } } GetItem (student_name) { Alert.alert(student_name); } componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/StudentsList.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) => <View style={{flex:1, flexDirection: 'column'}} > <TouchableOpacity onPress={this.GetItem.bind(this, rowData.student_name)} > <Text style={styles.textViewContainer} >{'id = ' + rowData.id}</Text> <Text style={styles.textViewContainer} >{'Name = ' + rowData.student_name}</Text> <Text style={styles.textViewContainer} >{'Phone Number = ' + rowData.student_phone_number}</Text> <Text style={styles.textViewContainer} >{'Subject = ' + rowData.student_subject}</Text> </TouchableOpacity> </View> } /> </View> ); } } const styles = StyleSheet.create({ MainContainer :{ // Setting up View inside content in Vertically center. justifyContent: 'center', flex:1, paddingTop: (Platform.OS === 'ios') ? 20 : 0, backgroundColor: '#00BCD4', padding: 5, }, textViewContainer: { textAlignVertical:'center', padding:10, fontSize: 20, color: '#fff', } }); AppRegistry.registerComponent('Project', () => Project); |
Screenshot in iOS device :
Screenshots in Android device :
Nice Tutorial Sir…
Thanks 🙂
I got an error that says : ” JSON Parse error: Unrecognized token ‘<' please help
Firas please check your DBConfig.php file is configured correctly .
yes you right Im using a Java EE Spring web app, the data that I was looking for were hidden cause of an error 401 so thats why React native showed me that error
Hey bro! im wondering, this code aplies if i want to do the same with Flatlist?
Bro to make multiple items using FlatList you can read my this tutorial https://reactnativecode.com/flatlist-using-json-parsing-data/ all you have to do is follow the ListView layout area and make a view with multiple items inside it.
but if we don’t have any data into mysql will show error ..
Syntax error : son parse error : unable to parse son string
In this case just check there is a value present on json’s 1st item and if there is no value then show a alert message.
nice work, its good to get all react-native tutorials from one website
Welcome Yagnik 🙂 .
this error is coming while i applied this same code
null is not an object(evaluating’e.cloneWithRows’)
Akhil you need to remove the App registry line and add export default at the starting of class name.
hey how to find specific value into json data file ?
for example in above example if i pass id “6” then it will be return name: “sonal” phone number: “1234567890” and subject: “english”
how to implement this?
is you found any solution for this?
iam still searching for this.
if you solved this
please inform me
Read our this tutorial this would help you : https://reactnativecode.com/add-search-bar-filter/
any mathod or function to convert responceJson to Array in react native?
Anil you can use JSON.stringify() method.
Thanks bro. Great work. Dont stop yours posts
Welcome Anderson 🙂 .
Helpfull tutorial. Go ahead and thanks alot.
Thanks bro 🙂 .
Hai bro, i followed your codes.but listview items not showing anything without no errors
Raja did you are using the same URL as i have did.
I am using firebase and following your code, In ComponentDidMount() I have my firebase code whenever I try to retrive data from firebase it says: TypeError: TypeError: undefined is not an object (evaluating ‘l.rowIdentities’)
Talha in DBConfig.php file what server username, password and database name you are putting .
How i can show the data on screen no using FlatList?
Diondir then which component you want to use ?
help me.
cant find variable” Myproject
export default Myproject = createStackNavigator(
{
First: { screen: MainActivity },
Second: { screen: SecondActivity }
});
Dhika this tutorial is on old version of react native.