naoufal / react-native-accordion

An Accordion Component for React Native
https://www.npmjs.com/package/react-native-accordion
437 stars 101 forks source link

First Item open & Close when others are selected #39

Open JohnDotOwl opened 7 years ago

JohnDotOwl commented 7 years ago

How do i set the first item to be open by default and others to close when another item is selected?

fxhereng commented 7 years ago

You can keep refs to each accordions, and in onPress function: toggle the other ones, I don't know if it's the best solution but it works.

It would be something like that:

//Keep refs in an array
accordionRefs = [];

_renderRow(rowData, sectionID, rowID) {
    const header = this.renderHeader(rowData, rowID);

    var content = (
      <View>
        <Text>This content is hidden in the accordion</Text>
      </View>
    );

    return (
      <Accordion
        ref={(ref) => this.accordionRefs[parseInt(rowID)] = ref} //Keep ref here
        header={header}
        content={content}
        easing='easeOutCubic'
        onPress={() => this.onPressSection(parseInt(rowID), this.accordionRefs)} />
    );
  }

onPressSection(rowID, accordionRefs) {
     //Toggle other accordions except of the one clicked
      for (let i = 0; i < accordionRefs.length; i++) {
        if (i != rowID && accordionRefs[i] != null) {
          accordionRefs[i].toggle();
        }
      }
    }

Hope it helps

efstathiosntonas commented 6 years ago

@fxhereng thanks for the snippet.

when using flatlist it won't toggle.

   _onPressSection(index, accordionRefs) {
        for (let i = 0; i < accordionRefs.length; i++) {
            if (i != index && accordionRefs[i] != null) {
                accordionRefs[i].toggle();
            }
        }
    }

    accordionRefs = [];

    _renderItems = ({item, index}) => {
        return (
            <Accordion
                ref={ref => this.accordionRefs[index] = ref}
                header={() => this._header(item)}
                content={this._content(item.categories)}
                duration={300}
                easing='easeOutCubic'
                underlayColor={'white'}
                onPress={() => {this._onPressSection(index, this.accordionRefs)}}
            />
        );
    };

  _womanTab = () => {
        return (
            <View style={styles.container}>
                <FlatList
                    data={CATEGORIES3}
                    key={CATEGORIES3.id}
                    renderItem={this._renderItems}
                />
            </View>
        );
    };

any clue why it won't attach to the ref in order to toggle it?

efstathiosntonas commented 6 years ago

It seemed that i was using react-native-tab-view with SceneMap that uses pure component and the screen won't re-render.