Create a Query Param Login Modal Route with React Router

Jason Brown

An example we’ll focus on is a login modal. We want to link to the modal, however it should be able to be linked and appear over any page dynamically. Depending on your route structure this can be tricky, so we’ll use a query param. So let’s explore how to setup a query param modal that can be rendered over any page.

createPortal will render React provided, to a different place in the DOM and ensure that all appropriate context is passed along as well. Think of it as a “transport this HTML somewhere else”. This allows for you to render something that makes sense hierarchically but functionally needs to exist somewhere else in the DOM.

The wrapping div will apply our styling, so it will be a fixed div covering the screen with a dark background. Upon click it will call a passed in onClick method which later we’ll use for closing the modal.

We pass in our children which means any React that we want will be rendered in our modal, and transported to modal_root.

The behavior we desire is that if the background is clicked that the modal closes. We can do this with the history prop passed in by React Router.

Additionally rather than referencing match.url which is the path is matched by React Router. So instead we use the location.pathname which will return the current path in URL minus the query params.

This technique of depending on a query param is great for when you have a lot of exact routes. It also would not make sense to have the path be a hard coded /profile/login. So depending on a query param is an easy solution.

We grab our params, and do a .get("login") to check the existence of the login query param. If it exists we return our login modal, otherwise nothing will return and nothing will render.

This is supported by all browsers except for IE. You do not need to use URLSearchParams you can parse and access the query params however you see fit.

We supply an object and provide a pathname which will be our match.url so the path that we are matching on, and then additionally a search key and pass in ?login=true so that it’s not undefined and will register accordingly with our URLSearchParams.

You can check out the code here https://github.com/codedailyio/ReactRouterModal and or check out the live demo.