Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect route changes using React Router in React?

I have a search component that is global to my application, and displays search results right at the top. Once the user does any sort of navigation, e.g., clicking a search result or using the back button on the browser, I want to reset the search: clear the results and the search input field.

Currently, I am handling this with a Context; I have a SearchContext.Provider that broadcasts the resetSearch function, and wherever I am handling navigation, I have consumers that invoke resetSearch before processing navigation (which I do programmatically with the useHistory hook).

This doesn't work for back button presses on the browser's controls (since that is something out of my control).

Is there an intermediate step before my Routes are rendered (or any browser navigation happens) that I can hook into, to make sure my resetSearch function is invoked?

As requested, here is the code:

// App.js
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);

const resetSearch = () => {
    setResults([]);
    setQuery("");
};

<SearchContext.Provider value={{ resetSearch }}>
    // all of my <Route /> components in this block
</SearchContext.Provider>
// BusRoute.js
const { resetSearch } = useContext(SearchContext);

const handleClick = stop => {
    resetSearch();
    history.push(`/stops/${stop}`);
};

return (
    // some other JSX
    <button onClick={() => handleClick(stop.code)}>{stop.name}</button>
);
like image 696
Fam Avatar asked Nov 14 '25 14:11

Fam


1 Answers

You can listen to history changes:

useEffect(() => {
  const unlisten = history.listen((location) => {
    console.log('new location: ', location)
    // do your magic things here
    // reset the search: clear the results and the search input field
  })
  return function cleanup() {
    unlisten()
  }
}, [])

You can use this effect in your parent component which controls your global search's value.

like image 74
Ajeet Shah Avatar answered Nov 17 '25 10:11

Ajeet Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!