react-native-accordion icon indicating copy to clipboard operation
react-native-accordion copied to clipboard

First Item open & Close when others are selected

Open JohnDotOwl opened this issue 9 years ago • 3 comments

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

JohnDotOwl avatar Oct 16 '16 04:10 JohnDotOwl

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

fxhereng avatar Mar 07 '17 11:03 fxhereng

@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 avatar Mar 19 '18 11:03 efstathiosntonas

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

efstathiosntonas avatar Mar 21 '18 11:03 efstathiosntonas