Creating an Accordion in React Native
Components like Accordion are not readily available in many frameworks and the developer needs to have a custom implementation for such requirements. An accordion can be simply created in React Native and does not any special library for its implementation.
Here we will first create a simple Accordion with some text and later move on to display a list with selectable elements
We will require some icons for our Accordion components hence we will use react native vector icons library for handy availability of icons.
Step 1: Setup new Project & install React Native Vector Icons library
1.1: Install Vector Icons Library : $ npm install react-native-vector-icons
1.2: Link Vector Icons Library: $ react-native link react-native-vector-icons
You can preview all available icons in this package here. You can skip this and instead use your images/icons if handy.
Step 2: Create Data for Accordion
We will create an array of objects for food menu dishes. For simple accordion we will consider the below data:
Step 3: Create an Accordion Component
Our Accordion component will have two props:
title: title for Accordion
data: Data for display in Accordion
We also need to hide the content (i.e data text)need to hide the description text on title click. We will use ( ^ ) icons from react-vector-icons to denote whether the accordion is expanded or collapsed. We will achieve this by maintaining a state (expanded) for it. Our complete Accordion Component looks like this:
Step 4: Using our Accordion Component
We have kept our data in the state which is passed to Accordion Component using an iterator.
So our complete App.js file looks like this:
So here’s our sweet looking Accordion :)
You can refer my GitHub repo for full source code for a simple accordion
Step 5: Adding FlatList to our Accordion Component
5.1: First we need to refactor our dummy data to have a list of objects in the data element. Now we will use the below data. The data element is an array of object with 2 properties
key: Key denotes the display text
value: value is a boolean flag which denotes whether it's selected or not.
5.2: Customizing our Accordion to have a list
We need to consider that the user will click on the list item and it should be represented as selected. We will achieve this by using the value field in the object. We will toggle its boolean value every time a user clicks on it.
We will use icons to denote them as selected or unselected.
Our new Accordion component will be like this:
So our new Accordion will look like this :)
That's all! We just created our own Accordion component with the list in React Native. You can also refer to my repo for the code.
Step 6: Adding Animations to Accordion
I have now added layout animations for the accordion and you can see the smooth transitions while expanding & collapsing of accordion elements
To learn more do check out my new post → Layout Animations in React Native