Skip to content
Advertisement

How to detect a query param appended to URL using pure React

I have an injected external widget in my React application that have some links and when clicking in these links a query param is appended to the URL.

Imagine something like this:

  • base url: http://localhost:8080/
  • url after adding the query param: http://localhost:8080/?shouldOpenModal

Is there any way to detect this appended query param to the URL using React? It’s important in here that the page isn’t fully reloaded, since there’s information that cannot be lost and we also can’t use external libraries such as React Router DOM (which is widely used in similar questions in here).

So far, to append the URL without triggering a reload is using this:

if (history.pushState) {
    const newUrl = window.location.protocol + "//" + 
                   window.location.host + 
                   window.location.pathname + '?stOpenBenefitsModal';
    window.history.pushState({path:newurl},'',newurl);
}

Advertisement

Answer

You also need to update some app state when update url to re-render your component tree:

....

[state, setState] = useState(window.location)

const navigate = (url)=>{
  window.history.push('','',url);
  setState(window.location)
}


const handlePopState = ()=>{
  setState(window.location)
}

useEffect(()=>{
  // sync back and forward browser button with state
  window.addEvenListener('popstate',handlePopState)
},[])

....

//render something based on state value
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement