Skip to content Skip to sidebar Skip to footer

React Native - How To Get Y Offset Value Of A View From Scrollview?

I am trying to get the scroll position of a view. But the value for Y offset to page which is not related to the view's position. ScrollView Hierarchy: - MyC

Solution 1:

View component has a property called onLayout. You can use this property to get the position of that component.

onLayout

Invoked on mount and layout changes with:

{nativeEvent: { layout: {x, y, width, height}}}

This event is fired immediately once the layout has been calculated, but the new layout may not yet be reflected on the screen at the time the event is received, especially if a layout animation is in progress.

Update

onLayout prop gives a position to the parent component. This means to find the position of SubView2, you need to get total of all the parent components (MyComponent2 + SubView1 + SubView2).

Sample

exportdefaultclassAppextendsComponent {
  state = {
    position: 0,
  };
  _onLayout = ({ nativeEvent: { layout: { x, y, width, height } } }) => {
    this.setState(prevState => ({
      position: prevState.position + y
    }));
  };
  componentDidMount() {
    setTimeout(() => {
      // This will scroll the view to SubView2this.scrollView.scrollTo({x: 0, y: this.state.position, animated: true})
    }, 5000);
  }
  render() {
    return (
      <ScrollViewstyle={styles.container}ref={(ref) => this.scrollView = ref}>
        <Viewstyle={styles.view}><Text>{'MyComponent1'}</Text></View><Viewstyle={[styles.view, { backgroundColor: 'blue'}]} onLayout={this._onLayout}><Text>{'MyComponent2'}</Text><Viewstyle={[styles.view, , { backgroundColor: 'green'}]} onLayout={this._onLayout}><Text>{'SubView1'}</Text><Viewstyle={[styles.view, { backgroundColor: 'yellow'}]} onLayout={this._onLayout}><Text>{'SubView2'}</Text></View></View></View></ScrollView>
    );
  }
} 

Post a Comment for "React Native - How To Get Y Offset Value Of A View From Scrollview?"