How to change page in ViewPager react-native

Viewed 7575

I'm using ViewPager in my app with react-native-step-indicator but I need to change the page upon using specific button.

Here is part of my code:

import ViewPager from 'react-native-viewpager';
import StepIndicator from 'react-native-step-indicator';

const PAGES = ['Business','Logo','Description'];

export default class UserSetup extends Component {
  constructor() {
    super();
    var dataSource = new ViewPager.DataSource({
      pageHasChanged: (p1, p2) => p1 !== p2,
    });
    this.state = {
      dataSource: dataSource.cloneWithPages(PAGES),
      currentPage:0,
      token: null,
      userId: null,
      name: "",
      address1: "",
      address2: "",
      city: "",
      country: "",
      zipcode: "",
      url: "",
      phone: "",
      description: "",
    }
  }
  render() {
    const { navigate } = this.props.navigation;
      return (...
        <View style={styles.stepIndicator}>
          <StepIndicator customStyles={indicatorStyles}
          currentPosition={this.state.currentPage}
          stepCount={3}
          labels={['Basic info','Logo','Description']} />
        </View>
        <ViewPager dataSource={this.state.dataSource}
          renderPage={this.renderViewPagerPage}
          onChangePage={(page) => {this.setState({currentPage:page})}}
          />
      </View>
      );
    }

Then in the first page I have a button and I need to change first page to second page when button is pressed. How can I do that?

3 Answers

Adding on to @LorisTujiba's answer. This code worked for me when I was trying to change the page on click of the button.

1. Declaration part for ref

const ref = React.useRef(PagerView);

2. Passing the ref

< PagerView initialPage={0} ref={ref}>

3. Change page on button click

ref.current.setPage(currentIndex + 1);

I found the solution, just need to include this in the ViewPager Options:

ref={(viewpager) => {this.viewpager = viewpager}}

And then setting in the button OnPress on the page like this:

this.viewpager.goToPage(NumberPage);
Related