n4kz / react-native-pages

Easy to use page view component
Other
376 stars 83 forks source link

How to access scrollToPage #8

Closed nicolastakashi closed 7 years ago

nicolastakashi commented 7 years ago

Sorry for my doubtful beast, but how do I use the crollToPage method I could not understand.

n4kz commented 7 years ago

You'll have to save reference to component first

  constructor(props) {
    super(props);

    this.updateRef = this.updateRef.bind(this);
  }

  updateRef(ref) {
    this._pages = ref;
  }

  render() {
    return <Pages ref={this.updateRef} />
  }

...and use it later to call methods


  onSomeEvent() {
    if (this._pages) {
      this._pages.scrollToPage(0);
    }
  }

Detailed ref usage is described here

metinvio commented 2 years ago

just use useRef()

import React, {useRef} from 'react';

const MyPages = () => {
  const pagerRef = useRef();

  return (
    <View style={{flex: 1}}>
      <Pages ref={pagerRef}>
        <View style={{flex: 1, backgroundColor: '#f2c748'}}>
          <TouchableOpacity
            onPress={() => {
              pagerRef.current.scrollToPage(1);
            }}>
            <Text>Hello</Text>
          </TouchableOpacity>
        </View>
        <View style={{flex: 1, backgroundColor: '#4987d8'}}></View>
        <View style={{flex: 1, backgroundColor: '#f24b69'}}></View>
      </Pages>
    </View>
  );
};