codeblockshub blog image

FlatList implementation in react native

React Native provide component called FlatList which is used for listing any type dynamic or static data. In this blog we will discuss how to implement a FlatList in React Native.

To use FlatList component import FlatList  from 'react-native' as below.

import {SafeAreaView,View,StyleSheet,Text,FlatList} from 'react-native';


Now define an array of data which will bind in flatlist, Here i am taking static data as below , you can have your own static or dynamic data from API endpoint.

const data=[
{key:"1",title:"Android"},
{key:"2",title:"IOS"},
{key:"3",title:"React"},
{key:"4",title:"Node JS"},
{key:"5",title:"Java"},
{key:"6",title:"PHP"},
{key:"7",title:"Javascript"},
];


Now call FlatList component with data-source.

 <FlatList
data={data}
renderItem={({item})=>this.renderItem(item)}
keyExtractor={item=>item.key}
/>


That's all, we done with flatlist so complete component will looks like

import React, {Component} from 'react';
import {SafeAreaView,View,StyleSheet,Text,FlatList,Alert} from 'react-native';
import Constants from 'expo-constants';
const data=[
{key:"1",title:"Android"},
{key:"2",title:"IOS"},
{key:"3",title:"React"},
{key:"4",title:"Node JS"},
{key:"5",title:"Java"},
{key:"6",title:"PHP"},
{key:"7",title:"Javascript"},
];
class FlatListScreen extends Component {
renderItem=(item)=>{
return(
<View key={item.key} style={styles.item}>
<Text>{item.title}Text>
>
)
}
render(){
return(
<SafeAreaView style={styles.container}>
<FlatList
data={data}
renderItem={({item})=>this.renderItem(item)}
keyExtractor={item=>item.key}
/>
SafeAreaView>
)
}
}
export default FlatListScreen;

const styles =StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
padding:10
},
item:{
padding:10,
borderWidth:1,
borderRadius:5,
borderColor:"#c1dec5",
marginBottom:10},
})


Now if want to display item title on touch of list item, or other operation on an item then modified your renderItem function as bellow

      showItem=(data)=>{
    Alert.alert(data);
    }
renderItem=(item)=>{
return(
<View key={item.key} style={styles.item}>
<TouchableOpacity onPress={()=>this.showItem(item.title)}>
<Text>{item.title}Text>
>
>
)
}

codeblockshub blog image

How to implement SectionList in react native

1. Import StyleSheet,Text,View,SectionList, SafeAreaView  Component in your class as below.

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
SectionList,
} from 'react-native';
import Constants from 'expo-constants';
import {SearchBar} from 'react-native-elements';


2. Declare an array of list to display on SectionList

const DATA = [
{
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
},
];

3. Set some style to your UI Elements

const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
marginHorizontal: 16,
},
item: {
padding: 10,
borderRadius:5,
borderWidth:1,
borderColor:"black",
marginVertical: 5,
},
header: {
fontSize: 20,
fontWeight:'bold'
},
title: {
fontSize: 16,
},
});


4. Create SectionList component inside your render function as below

return (
<SafeAreaView style={styles.container}>
<SectionList
stickySectionHeadersEnabled
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
</SafeAreaView>
);

In the above code snippet , sections holds the data to display in list . stickySectionHeadersEnabled is for sticky header section of the list.

5. Complete source code of component will as below

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
SectionList,
} from 'react-native';
import Constants from 'expo-constants';
import {SearchBar} from 'react-native-elements';

const DATA = [
{
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
},
];

function Item({ title }) {
return (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
}

export default class SectionListScreen extends Component{
render(){
return (
<SafeAreaView style={styles.container}>
<SectionList
stickySectionHeadersEnabled
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
</SafeAreaView>
);
}

}

const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
marginHorizontal: 16,
},
item: {
padding: 10,
borderRadius:5,
borderWidth:1,
borderColor:"black",
marginVertical: 5,
},
header: {
fontSize: 20,
fontWeight:'bold'
},
title: {
fontSize: 16,
},
});


codeblockshub blog image

How to implement Searchable FlatList in react native

When list become long its difficult to find items on list. So in this blog we will learn how to implement searchable FlatList in react native.

Import all required component as below.

import React, {Component} from 'react';
import {
SafeAreaView,
View,StyleSheet,
TouchableOpacity,
Text,
FlatList,
Alert} from 'react-native';
import Constants from 'expo-constants';
import {SearchBar} from 'react-native-elements';

Here SearchBar component using from 'react-native-elements' .

Lets first define an array of list for our FlatList

const data=[
{key:"1",title:"Android"},
{key:"2",title:"IOS"},
{key:"3",title:"React"},
{key:"4",title:"Node JS"},
{key:"5",title:"Java"},
{key:"6",title:"PHP"},
{key:"7",title:"Javascript"},
];

 

Now lets initialize  some state variable which will be use later.

constructor(){
super()
this.state={
data:data,
search:""
}
}


Now,  we need to add a search bar for FlatList so user can search the list . FlatList has a prop to add any custom component to its header which is useful as we’ll be adding a search component there.

renderHeader=()=>{
const { search } = this.state;
return(
<SearchBar
placeholder="Search Here"
lightTheme
onChangeText={text=>this.searchAction(text)}
autoCorrect={false}
value={search}
/>
)
}
searchAction=(text)=>{
const newData=data.filter(item=>{
const itemData=`${item.title.toUpperCase()}`;
const textData=text.toUpperCase();
return itemData.indexOf(textData) > -1;

});
this.setState({
data:newData,
search:text
});
}


In the above code snippet, seachAction function which will filter our existing list user input on seacrbar

So our flatList component will look like

<FlatList
data={this.state.data}
renderItem={({item})=>this.renderItem(item)}
keyExtractor={item=>item.key}
ListHeaderComponent={this.renderHeader}
>
FlatList>

Here ListHeaderComponet is the  property to add seacrh bar at  top of the FlatList.

So our complete component will be as bellow

import React, {Component} from 'react';
import {
SafeAreaView,
View,StyleSheet,
TouchableOpacity,
Text,
FlatList,
Alert} from 'react-native';
import Constants from 'expo-constants';
import {SearchBar} from 'react-native-elements';
const data=[
{key:"1",title:"Android"},
{key:"2",title:"IOS"},
{key:"3",title:"React"},
{key:"4",title:"Node JS"},
{key:"5",title:"Java"},
{key:"6",title:"PHP"},
{key:"7",title:"Javascript"},
];
class FlatListWithSearch extends Component {
constructor(){
super()
this.state={
data:data,
search:""
}
}
showItem=(data)=>{
Alert.alert(data);
}

renderHeader=()=>{
const { search } = this.state;
return(
<SearchBar
placeholder="Search Here"
lightTheme
onChangeText={text=>this.searchAction(text)}
autoCorrect={false}
value={search}
/>
)
}
searchAction=(text)=>{
const newData=data.filter(item=>{
const itemData=`${item.title.toUpperCase()}`;
const textData=text.toUpperCase();
return itemData.indexOf(textData) > -1;

});
this.setState({
data:newData,
search:text
});
}

renderItem=(item)=>{
return(
<View key={item.key} style={styles.item}>
<TouchableOpacity onPress={()=>this.showItem(item.title)}>
<Text>{item.title}Text>
TouchableOpacity>
View>
)
}
render(){
return(
<SafeAreaView style={styles.container}>
<FlatList
data={this.state.data}
renderItem={({item})=>this.renderItem(item)}
keyExtractor={item=>item.key}
ListHeaderComponent={this.renderHeader}
>
FlatList>
SafeAreaView>
)
}
}
export default FlatListWithSearch;

const styles =StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
padding:10
},
item:{
padding:10,
borderWidth:1,
borderRadius:5,
borderColor:"#c1dec5",
marginBottom:10},
})


codeblockshub blog image

How to implement an expandable SectionList in react native

Previously we learn how we can implement a SectionList  . In this blog we will learn how to make section list expandable.

Here we'll use a flag isExpanded in data list, Initially isExpanded is set to false for each data item in the list. In each click of header section we will change the value of isExpanded.

1. Declare the data  list or if you have dynamic data format the data as below

const DATA = [
{ isExpanded:false,
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
isExpanded:false,
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
isExpanded:false,
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
isExpanded:false,
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
isExpanded:false,
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
isExpanded:false,
},
];


2. Define constructor in your class and set state

constructor(){
super()
this.state={
listData:DATA
}
}

Here DATA list which we define above assign to listData for binding list data from state. If you have dynamic data the after fetching update state variable "listData" with new data .


3. Now set-up the SectionList component , here data source we are using from the state.

<SectionList
stickySectionHeadersEnabled
sections={this.state.listData}
keyExtractor={ (item, index) => item + index}
renderItem={
({ item,section }) => <Item title={item} section={section} />
}
renderSectionHeader={
({ section }) => (
<TouchableOpacity onPress={()=>this.expand(section.title)}>
<View style={{flexDirection:"row",justifyContent:'space-between'}}>
<Text style={styles.header}>{section.title}</Text>
{(section.isExpanded)?
(<FontAwesome name="caret-up" size={15}/>)
:
(<FontAwesome name="caret-down" size={15}/>) }
</View>
</TouchableOpacity>
)
}
/>

In renderItem component we are passing section data along with item, so we can check wether isExpanded is set true or false. If it is set to false then we will return an empty View, if true then we will return the list item.

function Item({ title,section }) {
console.log("data in props #####::"+JSON.stringify(section));
if(!section.isExpanded){
return (<View/> );
}else{
return (
<View style={styles.item}>
<Text style={styles.title}>{title}Text>
View>
);
}
}


expand() function is used for expanding the list item, so on each click of header section we are going to invoke the expand() function setting up the updated value of isExpanded flag as below. And along with update the state so list can render with updated data.

expand=(title)=>{
let existing=DATA.find(item=>item.title === title)
if(existing.isExpanded === false){
existing.isExpanded=true
}else{
existing.isExpanded=false
}

this.setState({
listData:DATA
})

}


4. That's all, our expandable sectionList is done. Full source code will look like below.

import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
SectionList,
TouchableOpacity
} from 'react-native';
import {FontAwesome,MaterialCommunityIcons} from 'react-native-vector-icons';
import Constants from 'expo-constants';
import {SearchBar} from 'react-native-elements';

const DATA = [
{ isExpanded:false,
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
isExpanded:false,
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
isExpanded:false,
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
isExpanded:false,
},
{
title: 'Drinks',
data: ['Water', 'Coke', 'Beer'],
isExpanded:false,
},
{
title: 'Desserts',
data: ['Cheese Cake', 'Ice Cream'],
isExpanded:false,
},
];

function Item({ title,section }) {
console.log("data in props #####::"+JSON.stringify(section));
if(!section.isExpanded){
return (<View/> );
}else{
return (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
}
}

export default class SectionListScreen extends Component{
constructor(){
super()
this.state={
listData:DATA
}
}
expand=(title)=>{
let existing=DATA.find(item=>item.title === title)
if(existing.isExpanded === false){
existing.isExpanded=true
}else{
existing.isExpanded=false
}

this.setState({
listData:DATA
})

}
render(){
return (
<SafeAreaView style={styles.container}>
<SectionList
stickySectionHeadersEnabled
sections={this.state.listData}
keyExtractor={
(item, index) => item + index
}
renderItem={
({ item,section }) => <Item title={item} section={section} />
}
renderSectionHeader={
({ section }) => (
<TouchableOpacity onPress={()=>this.expand(section.title)}>
<View style={{flexDirection:"row",
justifyContent:'space-between'}}>
<Text style={styles.header}>{section.title}</Text>
{(section.isExpanded)?
(<FontAwesome name="caret-up" size={15}/>)
:
(<FontAwesome name="caret-down" size={15}/>) }
</View>
</TouchableOpacity>
)
}
/>
</SafeAreaView>
);
}

}

const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: Constants.statusBarHeight,
marginHorizontal: 16,
},
item: {
padding: 10,
borderRadius:5,
borderWidth:1,
borderColor:"black",
marginVertical: 5,
},
header: {
fontSize: 20,
fontWeight:'bold'
},
title: {
fontSize: 16,
},
});
codeblockshub blog image

How to navigate without navigation props / Navigation from anywhere

We can get access to a navigator through a ref and pass it to the NavigationService which we will use for navigate from anywhere . Use this only with the top-level (root) navigator of your app.

step 1: Create a file NavigationService.js

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};


step 2:  Add the navigation ref in app.js as below


import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { AppNavigator } from './navigator';
import NavigationService from './NavigationService';
import { store } from './redux/store';


class App extends Component {
   render() {
     return (
      
                  ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }}
         />
      

     );
   }
}
export default App;

step 3 : To use of navigation ref , import  NavigationService and call the navigate function

import NavigationService from '../../NavigationService';
const checkAuth=(response)=>{
  if(response.status==='unauthorized'){
      NavigationService.navigate('Logout');
  }else {
    return true;
  }
}
export default checkAuth;


Most Read