React Native Scrolling Accordion Style Nav

Code to implement a collapsible accordion style navigation element in React Native, with the ability to scroll to each clicked item

TAGS: react,react native,javascript

04/16/2017

I’ve found it a bit difficult to find a good, performant, accordion-style navigation component in React Native, that isn’t too complicated. There is a pretty good one by Oblador, but it doesn’t account for items inside a scroll view. What I wanted to be able to do was have the appropriate accordion menu item animate to the top of the user’s device, and reveal its subcategory menu items.

scroll accordion in react native

I built a stripped down version of it in Exponent’s Codepen-style Snack app, and a more full featured version of it as an open source git repo here. It was built using the standard react native getting-started instructions, so you can follow those to get the project up and running. The code is pretty well annotated, but essentially it is three components: the scroll accordion, which holds touts that contain subcategory links . When you click a tout, that tout scrolls to the top of the user’s device, regardless of where they have scrolled inside the scrollView, and animates down a list of subcategory links.

The tricky part is trying to keep the code dynamic, such that your touts can be any height, and your subcategory links can vary in number per category. This example tries to do that by using PureComponents where necessary, and only doing measurement calculations on initial layout, so that when a tout is actually clicked, all we have to do is update the view as the height of the subcategory link container animates and the view scrolls.

I still need to implement the ability to automatically close the previous subcategory link container if another tout is clicked. Other than that here is the code. Let me know if you have any questions or improvements.