Search code examples
javascriptreactjspaginationserver-sidereact-table

How copy state of react-table to use value of page and pageSize


I used https://www.npmjs.com/package/react-table lib. have to fetch data for a table by the filters of the column. filter below:

      ...
      filterable: true,
      Filter: () => {
        return (
          <input
            ...
            onChange={e => this.handleSearchInput(e)}
          />
        );
      }

handleSearchInput method calls request to the server

    let params = {
      filter_fields: this.state.filter, 
      page_size: this.state.pageSize, //here should be state of a table 
      page: this.state.page  // e.g. **state.page** and state - should be arguments
    };
    Actions.getMUsers(params)...

so how should synchronize page and pageSize value from ReactTable component to use it in the request body


Solution

  • assuming you have pageSize and page in your initial component state, you can use some of ReactTable's built in props to handle page size changes and page changes:

    <ReactTable
        pageSizeOptions={this.state.pageSizeOptions} //Don't need this if you don't want it
        defaultPageSize={this.state.pageSize} // probably smart to have if you're using this as part of a query but not neccessary
        pageSize={this.state.pageSize}
        page={this.state.page}
        onPageChange={page => this.setState({page: page})
        onPageSizeChange={(pageSize, page) => {
          this.setState({ pageSize: pageSize, page: page });
        }}
        ...otherProps
    />
    

    Some important things to remember are that if you are updating the onPageChange andonPageSizeChange functions, you MUST also handle the page and pageSize props manually (just by setting them to the state value, as it appears above)

    Also shown above, you can give it a list of the page size options you'd like to include, and have a default page size by initializing your state's pageSize variable with a value (like 25)