Edgaras Karka
Edgaras Karka

Reputation: 7862

React router keep query params when changing route and back

I have a website with different pages based on react-router v4. Each page have url query based filters it means filter setting are stored on url like mysite.com/page1?filterKey=value.

My goal is to keep filter values on query when user back from another page ( mysite.com/page2).

Upvotes: 2

Views: 6915

Answers (3)

user14522826
user14522826

Reputation: 1

For example using a dropdown as a filter

use -->localStorage.setItem("companyDrpDwnValue")

on onChange event

and call the the below method to intialize the param on ComponentDidMount ,with which you were filtering the table

and filter the array with the filter param to get your filtered array

Upvotes: -1

Edgaras Karka
Edgaras Karka

Reputation: 7862

I found other one solutions using react hooks based global state:

const [podcastsUrlSearch, updateGlobalState] = useGlobalState('podcastsUrlSerach')
useLayoutEffect(() => {
  if (!isEqual(props.location.search, podcastsUrlSearch)) {
    updateGlobalState(props.location.search)
  }
  if (podcastsUrlSearch) {
    props.history.replace({ ...props.history.location, search: podcastsUrlSearch })
  }
}, [])

useLayoutEffect(() => {
  updateGlobalState(props.location.search)
}, [props.location.search])

Upvotes: 2

SoufianeL
SoufianeL

Reputation: 166

The only 2 ways I see is either to use redux as Will Jenkins suggested, or to set the state in the parent container (either App.js, or the file handling your routes) :

  • In the parent container, define the function
setQuery = query => this.setState({query})
  • Pass the function to the child component

  • In the child component, pass the query on componentDidMount :

componentDidMount (){
    this.setQuery( decodeURIComponent(querySearch(this.props.location.search).param) )
}

Upvotes: 2

Related Questions