How to Use Query Parameters With React.JS + React Router
What is a Query Parameter?
Query parameters are a defined set of parameters attached to the end of a url.
More simply, they are key=value pairs we can attach to a url, used as one of many ways to pass data to an application.
Some Pre-requisites
First this requires an additional dependency that you may be familiar with, react-router-dom.
To install: npm i --save react-router-dom
Step one: Wrap your project in a Router.
In your index.jsx
file, when we are rendering our project to the DOM you will have to wrap the outer-most component in a Router tag. This will allow us to have scope of the query params for the next step.
Step two: Writing a function to parse the query params
This snippet has a lot going on, so let’s step through it. Also I do want to note, for the snippet above I have used the useEffect method assuming we want to do something with the query params on mounting our component.