indapublic
indapublic

Reputation: 2318

React Native. Best way for scroll to element inside ScrollView

I have scroll view with some component.

<ScrollView ref={ref => this.contentRef = ref}>
    <SomeComponent ref={ref => this.targetRef = ref}
</ScrollView>

What is the best way for scroll to SomeComponent but limit to ScrollView height?

My try:

if (this.contentRef && this.targetRef) {
    const UIManager = NativeModules.UIManager;
    UIManager.measure(findNodeHandle(this.contentRef), (contentX, contentY, contentW, contentH) => {
    UIManager.measure(findNodeHandle(this.targetRef), (activeStepX, activeStepY) => {
        const h = Dimensions.get('window').height;
        if (activeStepY > contentH / 2) {
        this.contentRef.scrollTo({ x: 0, y: h, animated });
        } else {
            this.contentRef.scrollTo({ x: 0, y: contentH, animated });
        };
    });
    });
};

But if target very close to screen bottom, I have empty space on bottom (sorry, I need to hide any information).

enter image description here

But should to look like

enter image description here

Upvotes: 2

Views: 4821

Answers (1)

wijuwiju
wijuwiju

Reputation: 197

Something like using onLayout method

https://facebook.github.io/react-native/docs/view#onlayout

e.g

<ScrollView> 
    <YourComponent onLayout={this.onLayout()} />
</ScrollView>


    onLayout(e) {
      return e.nativeEvent.layout.h // e.g would be the height of your scroll view
    } 

Upvotes: 1

Related Questions