Create an expandable list with react native

j.doe picture j.doe · Oct 20, 2017 · Viewed 8.1k times · Source

I am presenting a list of items with this code

      <View>
        <Text style={styles.sectionHeadingStyle}>
          Categories
        </Text>
        <View style={styles.navSubSectionStyle}>

        {data.categories.map(category =>
          <Text key={category.id} >
            { (JSON.parse(category.name)) }
          </Text>
          )}
        </View>

I want to be able to expand/collapse the list, with animation, when I click on the "Category" text. Is there any react native element for that?

Answer

JainZz picture JainZz · Oct 20, 2017

Set initial state of collapse to false.

handleClick = () => {
    this.setState({
        collapse: !this.state.collapse
    })
}
<View>
    <TouchableHighlight onClick={this.handleClick}>
        <Text style={styles.sectionHeadingStyle}>
           Categories
        </Text>
    </TouchableHighlight>
    </View>
    {
        this.state.collapse ? 
        <View style={styles.navSubSectionStyle}>

            {data.categories.map(category =>
            <Text key={category.id} >
                { (JSON.parse(category.name)) }
            </Text>
            )}
        </View>
        : null

    }
</View>