Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS - using back button to get previous searches

Tags:

reactjs

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?

like image 752
Sternjobname Avatar asked Aug 05 '18 21:08

Sternjobname


People also ask

How navigate back to previous page in React JS?

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.

How do I see previous route history in React?

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.

How do you handle back button of browser in React?

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.


1 Answers

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>
    );
  }
}
like image 147
Tholle Avatar answered Oct 29 '22 10:10

Tholle