Introduction
This is an Example of Collapsible / Accordion / Expandable List View in React Native. To make a Collapsible / Accordion / Expandable View we will use react-native-collapsible
library.
As mobile application developers, we always have a limited area to draw our imagination and in some cases, we have lots of data to show. To solve this issue we have a view called Collapsible View which shows the important data on the top and if the user is interested in the content they can click to expand the view and can see the related data in detail.
This example will have a Single Collapsible View, Selectors, and Accordion View.
For those who have heard Accordion for the first time; Accordion is frequently used in HTML which is like expandable list in mobile development.
Collapsible
{/*Code for Single Collapsible Start*/}
<TouchableOpacity onPress={this.toggleExpanded}>
<View style={styles.header}>
<Text style={styles.headerText}>Single Collapsible</Text>
{/*Heading of Single Collapsible*/}
</View>
</TouchableOpacity>
{/*Content of Single Collapsible*/}
<Collapsible collapsed={this.state.collapsed} align="center">
<View style={styles.content}>
<Text style={{ textAlign: 'center' }}>
This is a dummy text of Single Collapsible View
</Text>
</View>
</Collapsible>
{/*Code for Single Collapsible Ends*/}
Accordion
<Accordion
activeSections={activeSections}
// For any default active section
sections={CONTENT}
// Title and content of accordion
touchableComponent={TouchableOpacity}
// Which type of touchable component you want
// It can be the following Touchables
// TouchableHighlight, TouchableNativeFeedback
// TouchableOpacity , TouchableWithoutFeedback
expandMultiple={multipleSelect}
// Do you want to expand mutiple at a time or single at a time
renderHeader={this.renderHeader}
// Header Component(View) to render
renderContent={this.renderContent}
// Content Component(View) to render
duration={400}
// Duration for Collapse and expand
onChange={setSections}
// Setting the state of active sections
/>
In this example, you will see
- Simple collapsible View.
- Accordion View (With Multiple/Single Expand).
- Selector Bar connects with Accordion View.
So Let’s get started.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependencies
To use Collapsible
and Accordion
component you need to install react-native-collapsible
and react-native-collapsible/Accordion
package.
To install this open the terminal and jump into your project
cd ProjectName
Run the following command
npm install react-native-collapsible --save
npm install react-native-collapsible/Accordion --save
We will use some animation to expand the view, for that you need to install react-native-animatable
package.
To use Animatable
component install using
npm install react-native-animatable --save
These commands will copy all the dependencies into your node_module directory.
Code for Collapsible – Accordion – Expandable View
Now Open App.js in any code editor and replace the code with the following code
App.js
// Example of Collapsible/Accordion/Expandable List View in React Native
// https://aboutreact.com/collapsible-accordion-expandable-view/
// import React in our code
import React, {useState} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
Switch,
ScrollView,
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
// import for the animation of Collapse and Expand
import * as Animatable from 'react-native-animatable';
// import for the collapsible/Expandable view
import Collapsible from 'react-native-collapsible';
// import for the Accordion view
import Accordion from 'react-native-collapsible/Accordion';
// Dummy content to show
// You can also use dynamic data by calling web service
const CONTENT = [
{
title: 'Terms and Conditions',
content:
'The following terms and conditions, together
with any referenced documents form a legal
agreement between you and your employer, employees,
agents, contractors and any other entity on whose
behalf you accept these terms',
},
{
title: 'Privacy Policy',
content:
'A Privacy Policy agreement is the agreement where you
specify if you collect personal data from your users,
what kind of personal data you collect and what you do
with that data.',
},
{
title: 'Return Policy',
content:
'Our Return & Refund Policy template lets you get
started with a Return and Refund Policy agreement.
This template is free to download and use. According to
TrueShip study, over 60% of customers review a Return/Refund
Policy before they make a purchasing decision.',
},
];
//To make the selector (Something like tabs)
const SELECTORS = [
{title: 'T&C', value: 0},
{title: 'Privacy Policy', value: 1},
{title: 'Return Policy', value: 2},
{title: 'Reset all'},
];
const App = () => {
// Default active selector
const [activeSections, setActiveSections] = useState([]);
// Collapsed condition for the single collapsible
const [collapsed, setCollapsed] = useState(true);
// MultipleSelect is for the Multiple Expand allowed
// True: Expand multiple at a time
// False: One can be expand at a time
const [multipleSelect, setMultipleSelect] = useState(false);
const toggleExpanded = () => {
// Toggling the state of single Collapsible
setCollapsed(!collapsed);
};
const setSections = (sections) => {
// Setting up a active section state
setActiveSections(
sections.includes(undefined) ? [] : sections
);
};
const renderHeader = (section, _, isActive) => {
// Accordion header view
return (
<Animatable.View
duration={400}
style={[
styles.header,
isActive ? styles.active : styles.inactive
]}
transition="backgroundColor">
<Text style={styles.headerText}>
{section.title}
</Text>
</Animatable.View>
);
};
const renderContent = (section, _, isActive) => {
// Accordion Content view
return (
<Animatable.View
duration={400}
style={[
styles.content,
isActive ? styles.active : styles.inactive
]}
transition="backgroundColor">
<Animatable.Text
animation={isActive ? 'bounceIn' : undefined}
style={{textAlign: 'center'}}>
{section.content}
</Animatable.Text>
</Animatable.View>
);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<ScrollView>
<Text style={styles.title}>
Example of Collapsible/Accordion/Expandable
Listview in React
Native
</Text>
{/*Code for Single Collapsible Start*/}
<TouchableOpacity onPress={toggleExpanded}>
<View style={styles.header}>
<Text style={styles.headerText}>
Single Collapsible
</Text>
{/*Heading of Single Collapsible*/}
</View>
</TouchableOpacity>
{/*Content of Single Collapsible*/}
<Collapsible
collapsed={collapsed}
align="center"
>
<View style={styles.content}>
<Text style={{textAlign: 'center'}}>
This is a dummy text of Single Collapsible View
</Text>
</View>
</Collapsible>
{/*Code for Single Collapsible Ends*/}
<View
style={{
backgroundColor: '#000',
height: 1,
marginTop: 10
}} />
<View style={styles.multipleToggle}>
<Text
style={styles.multipleToggle__title}
>
Multiple Expand Allowed?
</Text>
<Switch
value={multipleSelect}
onValueChange={(multipleSelect) =>
setMultipleSelect(multipleSelect)
}
/>
</View>
<Text style={styles.selectTitle}>
Please select below option to expand
</Text>
{/*Code for Selector starts here*/}
<View style={styles.selectors}>
{SELECTORS.map((selector) => (
<TouchableOpacity
key={selector.title}
onPress={
() => setSections([selector.value])
}
>
<View style={styles.selector}>
<Text
style={
activeSections.includes(selector.value) &&
styles.activeSelector
}>
{selector.title}
</Text>
</View>
</TouchableOpacity>
))}
</View>
{/*Code for Selector ends here*/}
{/*Code for Accordion/Expandable List starts here*/}
<Accordion
activeSections={activeSections}
// For any default active section
sections={CONTENT}
// Title and content of accordion
touchableComponent={TouchableOpacity}
// Which type of touchable component you want
// It can be the following Touchables
// TouchableHighlight, TouchableNativeFeedback
// TouchableOpacity , TouchableWithoutFeedback
expandMultiple={multipleSelect}
// If you want to expand multiple at a time
renderHeader={renderHeader}
// Header Component(View) to render
renderContent={renderContent}
// Content Component(View) to render
duration={400}
// Duration for Collapse and expand
onChange={setSections}
// Setting the state of active sections
/>
{/*Code for Accordion/Expandable List ends here*/}
</ScrollView>
</View>
</SafeAreaView>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
paddingTop: 30,
},
title: {
textAlign: 'center',
fontSize: 18,
fontWeight: '300',
marginBottom: 20,
},
header: {
backgroundColor: '#F5FCFF',
padding: 10,
},
headerText: {
textAlign: 'center',
fontSize: 16,
fontWeight: '500',
},
content: {
padding: 20,
backgroundColor: '#fff',
},
active: {
backgroundColor: 'rgba(255,255,255,1)',
},
inactive: {
backgroundColor: 'rgba(245,252,255,1)',
},
selectors: {
marginBottom: 10,
flexDirection: 'row',
justifyContent: 'center',
},
selector: {
backgroundColor: '#F5FCFF',
padding: 10,
},
activeSelector: {
fontWeight: 'bold',
},
selectTitle: {
fontSize: 14,
fontWeight: '500',
padding: 10,
textAlign: 'center',
},
multipleToggle: {
flexDirection: 'row',
justifyContent: 'center',
marginVertical: 30,
alignItems: 'center',
},
multipleToggle__title: {
fontSize: 16,
marginRight: 8,
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Output in Online Emulator
This is how you can make Collapsible / Accordion / Expandable ListView. If you have any doubts or want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Hi please create an example of collapsible side drawer(on click menu expand with sub menu).
HI i need accordion with sub accordion pls update
Can you please have a look at Tree View in React Native
while using “npm install react-native-collapsible/Accordion –save”, it displays a promt to signin to using your github account. After successfully signining in, it shows the following log:
npm ERR! code 128
npm ERR! command failed
npm ERR! command git –no-replace-objects ls-remote ssh://git@github.com/react-native-collapsible/Accordion.git
npm ERR! git@github.com: Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\shehr\AppData\Local\npm-cache\_logs\2021-09-03T13_08_51_383Z-debug.log
What to do in that case?