1 | import React from "react";
|
2 | import qs from "query-string";
|
3 | import PropTypes from "prop-types";
|
4 | export default WrappedComponent => {
|
5 | const WithURLSearch = class extends React.Component {
|
6 | static propTypes = {
|
7 | history: PropTypes.object.isRequired,
|
8 | location: PropTypes.object.isRequired,
|
9 | };
|
10 |
|
11 | componentDidUpdate(prevProps) {
|
12 | const { pageCount, currentPage } = this.props;
|
13 | if (
|
14 | prevProps.pageCount !== pageCount ||
|
15 | prevProps.currentPage !== currentPage
|
16 | ) {
|
17 | if ("currentPage" in this.props) {
|
18 | this.addSearchParams(currentPage, pageCount);
|
19 | } else {
|
20 | this.addSearchParams(1, pageCount);
|
21 | }
|
22 | }
|
23 | }
|
24 |
|
25 | addSearchParams(page, pageCount) {
|
26 | const history = this.props.history;
|
27 | const location = this.props.location;
|
28 | const search = qs.parse(location.search);
|
29 | const newSearch = {
|
30 | page: page,
|
31 | pageCount: pageCount,
|
32 | };
|
33 | const stringified = qs.stringify(Object.assign(search, newSearch));
|
34 | history.push({ pathname: location.pathname, search: stringified });
|
35 | }
|
36 |
|
37 | wrapPageChange = page => {
|
38 | const onPageChange = this.props.onPageChange;
|
39 | this.addSearchParams(page, this.props.pageCount);
|
40 | onPageChange(page);
|
41 | };
|
42 | render() {
|
43 | const { onPageChange, history, pathname, ...rest } = this.props;
|
44 |
|
45 | return <WrappedComponent {...rest} onPageChange={this.wrapPageChange} />;
|
46 | }
|
47 | };
|
48 | WithURLSearch.displayName = `WithURLSearch(${getDisplayName(
|
49 | WrappedComponent,
|
50 | )})`;
|
51 | return WithURLSearch;
|
52 | };
|
53 | function getDisplayName(WrappedComponent) {
|
54 | return WrappedComponent.displayName || WrappedComponent.name || "Component";
|
55 | }
|
56 |
|
\ | No newline at end of file |