forked from oblador/react-native-collapsible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Accordion.js
93 lines (80 loc) · 2.55 KB
/
Accordion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import React, {
Component,
PropTypes,
} from 'react';
import {
View,
TouchableHighlight,
} from 'react-native';
import Collapsible from './Collapsible';
const COLLAPSIBLE_PROPS = Object.keys(Collapsible.propTypes);
const VIEW_PROPS = Object.keys(View.propTypes);
class Accordion extends Component {
static propTypes = {
sections: PropTypes.array.isRequired,
renderHeader: PropTypes.func.isRequired,
renderContent: PropTypes.func.isRequired,
onChange: PropTypes.func,
align: PropTypes.oneOf(['top', 'center', 'bottom']),
duration: PropTypes.number,
easing: PropTypes.string,
initiallyActiveSection: PropTypes.number,
activeSection: PropTypes.oneOfType([
PropTypes.bool, // if false, closes all sections
PropTypes.number, // sets index of section to open
]),
underlayColor: PropTypes.string,
};
static defaultProps = {
underlayColor: 'black',
};
constructor(props) {
super(props);
// if activeSection not specified, default to initiallyActiveSection
this.state = {
activeSection: props.activeSection !== undefined ? props.activeSection : props.initiallyActiveSection,
};
}
_toggleSection(section) {
const activeSection = this.state.activeSection === section ? false : section;
if (this.props.activeSection === undefined) {
this.setState({ activeSection });
}
if (this.props.onChange) {
this.props.onChange(activeSection);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.activeSection !== undefined) {
this.setState({
activeSection: nextProps.activeSection,
});
}
}
render() {
let viewProps = {};
let collapsibleProps = {};
Object.keys(this.props).forEach((key) => {
if (COLLAPSIBLE_PROPS.indexOf(key) !== -1) {
collapsibleProps[key] = this.props[key];
} else if (VIEW_PROPS.indexOf(key) !== -1) {
viewProps[key] = this.props[key];
}
});
return (
<View {...viewProps}>
{this.props.sections.map((section, key) => (
<View key={key}>
<TouchableHighlight onPress={() => this._toggleSection(key)} underlayColor={this.props.underlayColor}>
{this.props.renderHeader(section, key, this.state.activeSection === key)}
</TouchableHighlight>
<Collapsible collapsed={this.state.activeSection !== key} {...collapsibleProps}>
{this.props.renderContent(section, key, this.state.activeSection === key)}
</Collapsible>
</View>
))}
</View>
);
}
}
module.exports = Accordion;