How to Add Accordion Component in React Native

Accordions are useful to show large data neatly by hiding and expanding the data. React Native doesn’t have its own accordion component. In this blog post, let’s check how to add an accordion component in react native.

In this react native example, we use Galio UI library which provides various useful components for react native. It’s a lightweight library and very simple to use.

Galio library uses react native vector icons library. Hence make sure to install react native vector icons properly in your project. You can follow installation instructions from here.

Now, install the Galio library using the command given below.

npm install galio-framework

In order to create an accordion component properly, we need to use two components of the Galio UI library named Block and Accordion.

Block is the main component and is needed to create any other components using the library. You can create an accordion component simply as given below.

<Block style={{ height: 200 }}>
  <Accordion dataArray={data} />
</Block>

The data passed down to the Accordion should have keys title, content and icon.

const data = [
  { title: "First Chapter", content: "Lorem ipsum dolor sit amet", 
    icon: {
      name: 'keyboard-arrow-up',
      family: 'material',
      size: 16,
    } 
 },
  { title: "2nd Chapter", content: "Lorem ipsum dolor sit amet" },
  { title: "3rd Chapter", content: "Lorem ipsum dolor sit amet" }
];
Copy to clipboardErrorCopied

Following is the complete react native accordion example.

import React, {Component} from 'react';
import {View, StyleSheet} from 'react-native';
import {Accordion, Block} from 'galio-framework';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [
        {
          title: 'First Lesson',
          content:
            'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum',
        },
        {title: 'Second Lesson', content: 'Lorem ipsum dolor sit amet'},
        {title: 'Third Lesson', content: 'Lorem ipsum dolor sit amet'},
        {title: 'Fourth Lesson', content: 'Lorem ipsum dolor sit amet'},
        {title: 'Fifth Lesson', content: 'Lorem ipsum dolor sit amet'},
      ],
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <Block style={styles.block}>
          <Accordion dataArray={this.state.data} opened={null} />
        </Block>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  block: {
    height: 300,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

And here’s the output of the example.

react native accordion

Leave a Reply

%d bloggers like this: