UNPKG

react-native-accordion-display

Version:
113 lines (91 loc) 2.42 kB
// @flow import React, { PureComponent } from 'react'; import { View, ScrollView, TouchableOpacity, LayoutAnimation, StyleSheet, UIManager } from 'react-native'; /** * Example usage: * <Accordion sections='ARRAY' renderHeader={FUNCTION} renderContent={FUNCTION} renderActiveHeader={FUNCTION} /> * */ var CustomAnimation = { duration: 300, create: { type: LayoutAnimation.Types.linear, property: LayoutAnimation.Properties.opacity, }, update: { type: LayoutAnimation.Types.easeInEaseOut }, }; type Props = { sections: Array<Object>, renderHeader: Function, renderContent: Function, renderActiveHeader?: Function }; type State = { activeIndex: number }; class Accordion extends PureComponent<Props, State> { state = { activeIndex: -1 }; componentWillMount() { UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true); } updateActiveIndex = (index: number) => { LayoutAnimation.configureNext(CustomAnimation); this.setState({ activeIndex: index }); } _renderSection = (item: any, index: number) => { const { activeIndex } = this.state; const { renderHeader, renderContent } = this.props; return ( <View style={styles.container} key={index}> {activeIndex === -1 && <TouchableOpacity activeOpacity={0.7} onPress={() => this.updateActiveIndex(index)}> {renderHeader(item)} </TouchableOpacity> } {activeIndex === index && <ScrollView style={styles.container}>{renderContent(item)}</ScrollView>} </View> ); } render() { const { activeIndex } = this.state; const { sections, renderHeader, renderActiveHeader } = this.props; return ( <View style={styles.container}> {activeIndex !== -1 && <TouchableOpacity activeOpacity={0.7} onPress={() => this.updateActiveIndex(-1)}> {renderActiveHeader !== undefined ? renderActiveHeader(sections[activeIndex]) : renderHeader(sections[activeIndex])} </TouchableOpacity> } <ScrollView style={styles.container}> {sections.map((item, index) => this._renderSection(item, index) )} </ScrollView> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1 } }); export default Accordion;