Real time filter functionality is recommended for every dynamic react native application who wish to Filter the custom JSON ListView. So in this tutorial we would going to create a react native application with JSON data ListView and filter that data using PHP script. So let’s get started 🙂 .
What we are doing in this project ( Project Description – Must Read ) :Â
We are creating a react native app with 2 activities classes using React Navigation Library. First activity name is MainActivity and Second activity name is SecondActivity. The MainActivity class is used to show only the Name of students from JSON fetching from MySQL database. Now we would add the onPress event on ListView and get the selected ListView item ID. After that using the React Navigation inbuilt method this.props.navigation.navigate we would open the SecondActivity and send the Selected Item ID along with it. Now we would receive the Item ID using this.props.navigation.state.params in SecondActivitySecondActivity and run a real time web call to server using Fetch() method. It would send the Item ID on server and on server we are using the PHP script to Get ID and fetch only given ID record from MySQL database. After successfully fetching the only selected record it would return us in JSON form, which we would receive and show inside Text component.
Contents in this project Apply Filter on JSON ListView Data Using PHP MySQL Android iOS Tutorial :
1. Create a fresh MySQL database on your Local / Online hosting server.
2. Create a table inside your MySQL database named as Student_Info_Table with 5 columns id, name, semester, department, phone_number like i did in below screenshot.
4. Create 3 PHP Script files :
DBConfig.php : The DBConfig.php file contains all the server information like Database Host Name, Database name, Database username and Database Password.
CollegeStudentsList.php : This file would fetch all the records from MySQL database and covert them into JSON.
Filter.php : This is used to filter the received ID from react native application and return the only given ID record object of single student.
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 CollegeStudentsList.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_Info_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 after running the CollegeStudentsList.php file on web browser :
Code for Filter.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 34 35 36 37 38 39 40 41 42 |
<?php // Importing DBConfig.php file. include 'DBConfig.php'; // Creating connection. $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName); // Getting the received JSON into $json variable. $json = file_get_contents('php://input'); // decoding the received JSON and store into $obj variable. $obj = json_decode($json,true); // Populate ID from JSON $obj array and store into $ID. $ID = $obj['id']; //Fetching the selected record. $CheckSQL = "SELECT * FROM Student_Info_Table WHERE id='$ID'"; $result = $con->query($CheckSQL); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $Item = $row; $json = json_encode($Item); } }else { echo "No Results Found."; } echo $json; $con->close(); ?> |
Now the server side coding part is complete 🙂 . Next step is to Start the app coding .
5. Start a fresh React Native project. If you don’t know how then read my this tutorial.
6. Download and Install the React Navigation library inside your react native project by opening your project name folder into command prompt / terminal and execute the below command. The React Navigation library is used to add multiple activities in react native project.
1 |
npm install --save react-navigation |
Screenshot after installing the library :
7. Open your project’s App.js file and import StyleSheet, Text, View, ListView and ActivityIndicator component.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, ActivityIndicator } from 'react-native'; |
8. Import the Stack Navigator module from react navigation library.
1 |
import { StackNavigator } from 'react-navigation'; |
9. Create the first class named as MainActivity that extends the component. This would be our First main activity class.
1 2 3 4 |
class MainActivity extends Component { } |
10. Create navigationOptions inside MainActivity. The navigationOptions is used to set the activity Title which would show inside the Action Title bar of application.
1 2 3 4 5 6 7 8 |
class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; } |
11. Now create constructor inside MainActivity and inside constructor make a State named as isLoading. This State is used to show and hide the ActivityIndicator component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; constructor(props) { super(props); this.state = { isLoading: true } } } |
12. Create a function named as OpenSecondActivity() and pass id as argument inside it. This function is used to Open SecondActivity and with it we would also send the selected id to next activity using ListViewClickItemHolder object.
1 2 3 4 5 |
OpenSecondActivity(id) { this.props.navigation.navigate('Second', { ListViewClickItemHolder: id }); } |
13. Create componentDidMount() method. This is a pre define inbuilt method, which would call automatically on application starting time. Now define the fetch() web api inside componentDidMount() method. This would parse the complete JSON.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/CollegeStudentsList.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); }); } |
14. Create a function named as ListViewItemSeparator(). This is used to show a divider line between each ListView item in MainActivity.
1 2 3 4 5 6 7 8 9 10 11 |
ListViewItemSeparator = () => { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#000", }} /> ); } |
15. Set a IF condition inside render’s block and using the State check and hide the ActivityIndicator after done loading JSON data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( ); } |
16. Create a ListView component inside render’s return block in MainActivity . We are only showing the Student name from JSON data.
dataSource : Set the JSON ListView data source.
renderSeparator : Call the ListViewItemSeparator() method which would display item separator line.
renderRow : Render the Row data from Data source.
onPress : Call the OpenSecondActivity() function and pass the ID inside it using argument.
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 |
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.OpenSecondActivity.bind(this, rowData.id)}> {rowData.name} </Text>} /> </View> ); } |
17. Complete Source code for MainActivity class :
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 |
class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; constructor(props) { super(props); this.state = { isLoading: true } } OpenSecondActivity(id) { this.props.navigation.navigate('Second', { ListViewClickItemHolder: id }); } componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/CollegeStudentsList.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.OpenSecondActivity.bind(this, rowData.id)}> {rowData.name} </Text>} /> </View> ); } } |
Screenshot of MainActivity :
18. Now create the SecondActivity Class. This would be our Filter record class.
1 2 3 4 |
class SecondActivity extends Component { } |
19. Set activity Title using navigationOptions .
1 2 3 4 |
static navigationOptions = { title: 'SecondActivity', }; |
20. Create constructor and make 5 state variables named as IdHolder, NameHolder, SemesterHolder, DepartmentHolder and PhoneNumberHolder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
constructor(props) { super(props) this.state={ IdHolder : '', NameHolder : '', SemesterHolder : '', DepartmentHolder : '', PhoneNumberHolder : '' } } |
21. Create componentDidMount() method inside SecondActivity and call the Fetch() Web API. Now receive the sent id using this.props.navigation.state.params.ListViewClickItemHolder and pass it with id object. Now after come the response into responseJson array, we would pop up the records and store into each State .
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 |
componentDidMount(){ fetch('https://reactnativecode.000webhostapp.com/Filter.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ // Getting the id. id: this.props.navigation.state.params.ListViewClickItemHolder }) }).then((response) => response.json()) .then((responseJson) => { this.setState({ IdHolder : responseJson[0].id, NameHolder : responseJson[0].name, SemesterHolder : responseJson[0].semester, DepartmentHolder : responseJson[0].department, PhoneNumberHolder : responseJson[0].phone_number }) }).catch((error) => { console.error(error); }); } |
22. Create 5 Text component inside render’s return block. Each component is used to display a Filtered Record.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
render() { return( <View style = { styles.MainContainer }> <View style={{flex:1, flexDirection: 'column'}} > <Text style={styles.textViewContainer} > {'id = ' + this.state.IdHolder} </Text> <Text style={styles.textViewContainer} > {'Name = ' + this.state.NameHolder} </Text> <Text style={styles.textViewContainer} > {'Department = ' + this.state.DepartmentHolder} </Text> <Text style={styles.textViewContainer} > {'Semester = ' + this.state.SemesterHolder} </Text> <Text style={styles.textViewContainer} > {'Phone Number = ' + this.state.PhoneNumberHolder} </Text> </View> </View> ); } |
23. Complete Source code for SecondActivity Class :
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 |
class SecondActivity extends Component { static navigationOptions = { title: 'SecondActivity', }; constructor(props) { super(props) this.state={ IdHolder : '', NameHolder : '', SemesterHolder : '', DepartmentHolder : '', PhoneNumberHolder : '' } } componentDidMount(){ fetch('https://reactnativecode.000webhostapp.com/Filter.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ // Getting the id. id: this.props.navigation.state.params.ListViewClickItemHolder }) }).then((response) => response.json()) .then((responseJson) => { this.setState({ IdHolder : responseJson[0].id, NameHolder : responseJson[0].name, SemesterHolder : responseJson[0].semester, DepartmentHolder : responseJson[0].department, PhoneNumberHolder : responseJson[0].phone_number }) }).catch((error) => { console.error(error); }); } render() { return( <View style = { styles.MainContainer }> <View style={{flex:1, flexDirection: 'column'}} > <Text style={styles.textViewContainer} > {'id = ' + this.state.IdHolder} </Text> <Text style={styles.textViewContainer} > {'Name = ' + this.state.NameHolder} </Text> <Text style={styles.textViewContainer} > {'Department = ' + this.state.DepartmentHolder} </Text> <Text style={styles.textViewContainer} > {'Semester = ' + this.state.SemesterHolder} </Text> <Text style={styles.textViewContainer} > {'Phone Number = ' + this.state.PhoneNumberHolder} </Text> </View> </View> ); } } |
Screenshot of Second Activity with record :
24. Now create the StackNavigator method which would tell the project about present classes and which class is call first. This step is very important.
1 2 3 4 5 6 |
export default Myproject = StackNavigator( { First: { screen: MainActivity }, Second: { screen: SecondActivity } }); |
25. Create Custom Style sheet for all the Views and Text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
const styles = StyleSheet.create( { MainContainer: { justifyContent: 'center', flex:1, margin: 10 }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, }, textViewContainer: { padding:5, fontSize: 20, color: '#000', } }); |
26. Complete source code for App.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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, ActivityIndicator } from 'react-native'; import { StackNavigator } from 'react-navigation'; class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; constructor(props) { super(props); this.state = { isLoading: true } } OpenSecondActivity(id) { this.props.navigation.navigate('Second', { ListViewClickItemHolder: id }); } componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/CollegeStudentsList.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.OpenSecondActivity.bind(this, rowData.id)}> {rowData.name} </Text>} /> </View> ); } } class SecondActivity extends Component { static navigationOptions = { title: 'SecondActivity', }; constructor(props) { super(props) this.state={ IdHolder : '', NameHolder : '', SemesterHolder : '', DepartmentHolder : '', PhoneNumberHolder : '' } } componentDidMount(){ fetch('https://reactnativecode.000webhostapp.com/Filter.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ // Getting the id. id: this.props.navigation.state.params.ListViewClickItemHolder }) }).then((response) => response.json()) .then((responseJson) => { this.setState({ IdHolder : responseJson[0].id, NameHolder : responseJson[0].name, SemesterHolder : responseJson[0].semester, DepartmentHolder : responseJson[0].department, PhoneNumberHolder : responseJson[0].phone_number }) }).catch((error) => { console.error(error); }); } render() { return( <View style = { styles.MainContainer }> <View style={{flex:1, flexDirection: 'column'}} > <Text style={styles.textViewContainer} > {'id = ' + this.state.IdHolder} </Text> <Text style={styles.textViewContainer} > {'Name = ' + this.state.NameHolder} </Text> <Text style={styles.textViewContainer} > {'Department = ' + this.state.DepartmentHolder} </Text> <Text style={styles.textViewContainer} > {'Semester = ' + this.state.SemesterHolder} </Text> <Text style={styles.textViewContainer} > {'Phone Number = ' + this.state.PhoneNumberHolder} </Text> </View> </View> ); } } export default Myproject = StackNavigator( { First: { screen: MainActivity }, Second: { screen: SecondActivity } }); const styles = StyleSheet.create( { MainContainer: { justifyContent: 'center', flex:1, margin: 10 }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, }, textViewContainer: { padding:5, fontSize: 20, color: '#000', } }); |
Screenshots in android mobile phone application :
Screenshot in iOS mobile application :
bro how i will make dropdown items when clicked and fetch data from mysql ??
Sharoon you can read our this tutorial https://reactnativecode.com/create-picker-spinner-using-dynamic-json-data/ this would surely help you 🙂 .
bro how to import import StyleSheet, Text, View, ListView and ActivityIndicator component. iam new to react native kindly guide me
Just use the below lines to import the component in your project, NOW IN in the second line just type the component name in the curly bracket block.
import React, { Component } from ‘react’;
import { StyleSheet, Text, View, ListView, ActivityIndicator } from ‘react-native’;
Hello,
Can you please explain , How to perform Same CRUD Operations with Asp.Net C# and Ms Sql Server?
Sorry, Swapnil i don’t work in ASP.NET C# .
amigo una pregunta como hago si tengo una tabla y adentro otras dos tablas por ejemplo Student_Info_Table y adentro de esta tabla tengo dos mas que se llaman “id” y “nombre” y adentro de nombre esta la informacion que yo quiero mostrar, como hago para mostrarla?
Sir please make query in English .
friend a question as I do if I have a table and in other two tables for example Student_Info_Table and inside this table I have two more that are called “id” and “name” and inside the name is the information that I want to show, as I do for show it?
Angle yes you can show it easily but please explain your question more briefly ? So i can help in right way .
ok, thanks for responding, what I want to do is put two functions with different php files and call them in different ListView to show me the columns of the two files. since with its code I can only reference or call a single php file
Angel you want to load two listview and each with different PHP file so that’s very easy just make PHP files and get data from same table in both then use that file to parse JSON.
Hi, it get very very slow when it try to fetch a huge json file which contain at least 1000++ record. So is there any way can speed up the speed to retrieve all the json data?
Kelly after filter process you need to put the Infinite ListView so it will not load more then defined records. This will make the process faster. Read my this tutorial this would help you : https://reactnativecode.com/infinite-list-flatlist-pagination-load-more-data/ .
sir um failing display images only getting any thing l can use to filter images as well
Jay please be more specific you want to filter the image also ?
Hi.How we list user information when textinput enters a user id?
You need to send the user ID on server using fetch() API then on server we would use the ID to filter and and select the current record after selecting the record we would return the record details to application.
sir how to display images with mysql from listview selected…….thanks
Amad you want to filter the data and also filter the image data .
how do i fetch from api when user is searching by a string .
You want to implement real time searching ?
I want to print some content besides name in the main activity [on the left side].
How can I do it/
Akash you want to display name on the screen ? Please explain your query more briefly.
Hi! If there’s no data to show in the list, I want to show text “No Data” in the app. What should i do in the php and react native code? because using your code if there’s no data it will error like this [SyntaxError: JSON Parse error: Unexpected identifier “No”]. Thankyou
Farah you can put a condition at the end of react native code that check the data is == null or == ” then it will show a alert message.
hi bro . thanks for this education. i have this data in my database :
[{“id”:”1″,”tmb”:”23\/5\/96″,”name”:”ehsan”,”family”:”kharaman”},{“id”:”5″,”tmb”:”32\/12\/3333″,”name”:”mani”,”family”:”kharad”}]
this data show in consol chrom , now i would get only name:mani in second object and show in my app. but i cant it. my code is :
import React, {Component} from ‘react’;
import {View, Text} from ‘react-native’;
class App extends Component {
state = {
data: [”],
};
componentDidMount = () => {
fetch(‘http://192.168.1.34/karbar/select.php’, {
method: ‘GET’,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
this.setState({
data: responseJson,
});
})
.catch(error => {
console.error(error);
});
};
render() {
return (
{this.state.data[0].family}
);
}
}
export default App;
please help me for solve this problem bro.thanks
any guide to to help or updated post for this task? ListView is deprecated?
Craig i am working on this to implement on Flatlist . Will post the tutorial soon 🙂 .
I think I have figured it out but being new to react I would like to see your implementation and would be a big help to others, thanks for the great tutorials.
This is perfect. Thank you
Welcome Nkweti 🙂 .
sir, can you make tutorial using flatlist, cause listvies has been deleted