So I've written a little single page app which queries an API and returns a bunch of results which I display to the user underneath the input field where they enter their search term.
Each time I enter a new search term and press enter the API is re-queried and the page is updated with new results.
However, I'd like to be able to click the back button in my browser and go back through my previous search results. How would I do that?
To go back to the previous page, pass -1 as a parameter to the navigate() function, e.g. navigate(-1) . Calling navigate with -1 is the same as hitting the back button. Similarly, you can call the navigate function with -2 to go 2 pages back.
To detect previous path in React Router, we can set the state property to an object with the location. pathname as the value. <Link to={{ pathname: "/nextpath", state: { prevPath: location.
It depends on the type of Router you use in React. If you use BrowserRouter from react-router (not available in react-router v4 though), as mentioned above, you can use the action 'POP' to intercept the browser back button.
You could use React Router for this, and set it up so that each time you submit the search form you push a new entry to the history
object. You could then use the componentDidUpdate
hook to call your API when the URL parameter change.
Example
import createHistory from "history/createBrowserHistory";
const history = createHistory();
class Page extends React.Component {
state = {
value: "",
query: "",
data: ["foo", "bar", "test"],
filteredData: []
};
componentDidMount() {
this.setQuery();
}
componentDidUpdate(prevProps) {
if (prevProps.match.params.query !== this.props.match.params.query) {
this.setQuery();
}
}
setQuery = () => {
const { query = "" } = this.props.match.params;
const filteredData = this.state.data.filter(element =>
element.toLowerCase().includes(query.toLowerCase())
);
this.setState({ value: query, query, filteredData });
};
onChange = event => {
this.setState({ value: event.target.value });
};
onSubmit = event => {
event.preventDefault();
history.push(`/${this.state.value}`);
};
render() {
const { value, filteredData } = this.state;
return (
<div>
<form onSubmit={this.onSubmit}>
<input value={value} onChange={this.onChange} />
<input type="submit" value="Search" />
{filteredData.map(element => <div key={element}> {element} </div>)}
</form>
</div>
);
}
}
class App extends React.Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/:query?" component={Page} />
</Switch>
</Router>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With