2
\$\begingroup\$

I want to create react app with paging, which will keep state on page reloading.
I'm using react-router-dom and my own Paging component.
Currently I'm passing updateRoute function into SmthWithPaging component.

Is there simpler (or just correct?) way to update route inside component?

Surely, I can do it inside SmthWithPaging component by spliting path by /, replace the number and push new path to history. But in this case child component will have some knowlege about parent component and how its routing works. Which is undesirable.

App.js

import React, {Component}  from 'react';
import {BrowserRouter as Router, Route}  from 'react-router-dom';
import SmthWithPaging from './SmthWithPaging.js';

class App extends Component {
  render() {
    return (
      <Router>
        <Route
          path='page/:number'
          render={ ({history, match}) => (
            <SmthWithPaging
              currentPage={match.params.number}
              updateRoute={number =>
                history.push(match.path.replace(':number', number))}
            />
          )}
        />
      </Router >
    );
  }
}

SmthWithPaging.js

import React, {Component}  from 'react';
import Paging from './Paging.js';

class SmthWithPaging extends Component {
  constructor(props) {
    this.state = {currentPage: props.currentPage};
    this.updateRoute = props.updateRoute;
    this._handlePageChange = this._handlePageChange.bind(this);
  }

  async _handlePageChange(pageNumber) {
    this.updateRoute(pageNumber);
    //fetch some data related to the page and set it to the state
    this.setState({currentPage: pageNumber});
  }

  render() {
    return (
      //render some page related data
      <Paging
        onPageChange={this._handlePageChange}
        activePage={this.state.currentPage}
        pageCount={10}
      />
    );
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.