Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a scrollspy in react native with ScrollView?

I have a ScrollView component with different elements say:

<ScrollView>

    <Item1/>

    <Item2/>

    <Item3/>

</ScrollView>

I now have a tab which I need to highlight each tab item based on the current section the user is viewing in the scroll view. For example, if the user is viewing/scrolled to <Item2/> in the scroll view, then I should highlight item2 icon in the tab.

Also, if the user clicks on a tab item, it should automatically make the scrollview scroll to that respective item's section.

Is there any way to implement this scrollspy functionality in react native?

like image 304
Dani Akash Avatar asked Jan 03 '23 09:01

Dani Akash


1 Answers

To achieve desired behavior you need to combine couple of things.

  1. ScrollView has a method called scrollTo which let's you scroll to the desired position of the content.
  2. To be able to detect what is the ScrollView's current position you need to use onScroll property. You can combine this property with scrollEventThrottle to get a better accuracy.
  3. To get the each item's position inside the ScrollView you need to implement onLayout property for each item.

Below is a small sample app to show how to implement above steps.

const Item = props => (
  <View
    style={{ minHeight: 500 }}
    onLayout={e => props.onItemLayout(e, props.index)}>
    <Text>{`Item ${props.index}`}</Text>
  </View>
);

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      sections: [1, 2, 3],
      currentSection: 1
    };
  }
  moveToSetion = section => {
    // scroll view to section
    this.scrollView.scrollTo({ x: 0, y: this.state[section], animated: true });
    // set state to current section
    this.setState({ currentSection: section });
  };
  onItemLayout = ({ nativeEvent: { layout: { x, y, width, height } } }, section) => {
    // setting each items position
    this.setState({ [section]: y });
  };
  onScroll = ({ nativeEvent: { contentOffset: { y, x } } }) => {
    let _currentSection;
    // loop sections to calculate which section scrollview is on
    this.state.sections.forEach((section) => {
      // adding 15 to calculate Text's height
      if((y + 15) > this.state[section]) _currentSection = section
    })
    // settint the currentSection to the calculated current section
    this.setState({ currentSection: _currentSection })
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          {this.state.sections.map(section => (
            <Button
              key={section}
              title={`Section ${section}`}
              color={this.state.currentSection === section ? 'red' : 'blue'}
              onPress={() => this.moveToSetion(section)}
            />
          ))}
        </View>
        <ScrollView
          style={styles.scrollView}
          ref={ref => (this.scrollView = ref)}
          scrollEventThrottle={100}
          onScroll={this.onScroll}>
          {this.state.sections.map(section => (
            <Item
              key={section}
              index={section}
              onItemLayout={this.onItemLayout}
            />
          ))}
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    position: 'fixed',
    top: 0,
  },
  scrollView: {
    paddingLeft: 15,
    paddingRight: 15
  }
});
like image 197
bennygenel Avatar answered Jan 05 '23 14:01

bennygenel