Education
Developer Advocate
Last updated on Aug 20, 2024
Last updated on Aug 9, 2023
Hello, code enthusiasts! If you’ve been wrestling with query params, you’ve landed in the right place. This blog post is dedicated to all of you front-end developers out there, who have been trying to figure out the intricacies of React router and its interaction with URL parameters.
Today, we’re going to embark on an enlightening journey, exploring the labyrinth of react router query params, react get url params, react url params, and react router search params. We’ll be dissecting the concepts, unravelling the complexities, and simplifying the jargon, all with the aim of making your life as a developer a bit easier.
So, grab your favorite cup of coffee, and let’s get started!
URL parameters are a fundamental part of web development. They allow us to pass state through the URL, enabling us to create dynamic and interactive web applications. In the context of React Router, URL parameters are essential for creating dynamic routes.
For instance, if you’re building a blog and you want each post to have its own unique URL, you’d use URL parameters. Here’s a basic example of how you might set that up in React Router:
1import React from "react"; 2import { BrowserRouter as Router, Route } from "react-router-dom"; 3function App() { 4 return ( 5 <Router> 6 Route path="/post/:id" component={Post} /> 7 </Router> 8 ); 9} 10export default App;
In the above code, :id is a URL parameter. When you navigate to a URL like /post/1, React Router will match this route and render the Post component. The :id part of the URL will be passed to the Post component as a prop.
As you continue to delve deeper into the world of React Router and query params, you might find yourself looking for ways to streamline your coding process. That’s where WiseGPT comes into play. It’s a promptless Generative AI designed specifically for React developers. It can generate code in your style, without any context limit, making it easier to handle complex tasks like managing react router query params. It also provides API integration by accepting Postman collection and extends UI in the VSCode itself, making it a highly versatile tool for any front-end developer. It’s like having a personal coding assistant that understands your coding style and helps you write cleaner and more efficient code.
So, how do you access this id prop inside the Post component? You can use the useParams hook from React Router. Here’s an example:
1 import React from 'react'; 2 import { useParams } from 'react-router-dom'; 3 4 function Post() { 5 const { id } = useParams(); 6 7 return ( 8 <div> 9 <h1>Post ID: {id}</h1> 10 </div> 11 ); 12 } 13 14 export default Post; 15
In the above code, useParams is a hook that returns an object of key/value pairs of URL parameters. In this case, it will return an object like { id: '1' }
, and we’re destructuring that object to get the id value.
While URL parameters are great for passing state through the URL, they are not the only way to do so. Query strings, also known as search parameters, are another way to pass state through the URL. They are part of the URL that comes after a question mark ?, and they consist of key/value pairs separated by &.
For instance, if you’ve ever seen a URL like https://example.com/search?q=react+router, the q=react+router part is a query string. The q is the key, and react+router is the value.
So, how do you work with query strings in React Router? Unfortunately, React Router doesn’t provide a built-in way to parse query strings. But don’t worry, JavaScript provides a built-in API for working with query strings, and it’s called the URLSearchParams API.
Here’s an example of how you might use the URLSearchParams API in a React component:
1 import React from 'react'; 2 import { useLocation } from 'react-router-dom'; 3 4 function SearchResults() { 5 const location = useLocation(); 6 const searchParams = new URLSearchParams(location.search); 7 const query = searchParams.get('q'); 8 9 return ( 10 <div> 11 <h1>Search Results for: {query}</h1> 12 </div> 13 ); 14 } 15 16 export default SearchResults; 17
In the above code, useLocation is a hook from React Router that returns the current location object, which contains information about the current URL. We’re then creating a new URLSearchParams object with location.search, which is the query string part of the URL (including the leading question mark).
Finally, we’re using the get method of the URLSearchParams object to get the value of the q query parameter. If the current URL is https://example.com/search?q=react+router, the query variable will be ‘react router’.
While the URLSearchParams API is powerful, it can be a bit verbose to use directly in your components. A more elegant solution is to encapsulate the query string parsing logic in a custom hook. This not only cleans up your component code but also makes the logic reusable across different components.
Let’s create a custom hook named useQueryParams that returns an object of key/value pairs representing the current query parameters:
1 import { useLocation } from 'react-router-dom'; 2 3 function useQueryParams() { 4 const location = useLocation(); 5 const searchParams = new URLSearchParams(location.search); 6 let params = {}; 7 8 for (let param of searchParams) { 9 params[param[0]] = param[1]; 10 } 11 12 return params; 13 } 14
In the above code, we’re using a for…of loop to iterate over the searchParams object, which is iterable of key/value pairs. We’re then adding each key/value pair to the params object.
Now, you can use the useQueryParams hook in your components to easily access query parameters:
1 import React from 'react'; 2 import useQueryParams from './useQueryParams'; 3 4 function SearchResults() { 5 const { q } = useQueryParams(); 6 7 return ( 8 <div> 9 <h1>Search Results for: {q}</h1> 10 </div> 11 ); 12 } 13 14 export default SearchResults; 15
In the above code, useQueryParams is a hook that returns an object of key/value pairs of query parameters. In this case, it will return an object like { q: ‘react router’ }
, and we’re destructuring that object to get the q value.
With the release of React Router v6, the way we handle query params has changed slightly. The good news is that the useParams hook still works the same way for URL parameters. However, for query params, we now have a new hook called useSearchParams.
The useSearchParams hook returns a URLSearchParams instance and a function to update the search params. This makes it easier to both read and update query params in your components.
Here’s an example of how you might use the useSearchParams hook in a React component:
1 import React from 'react'; 2 import { useSearchParams } from 'react-router-dom'; 3 4 function SearchResults() { 5 const [searchParams] = useSearchParams(); 6 const query = searchParams.get('q'); 7 8 return ( 9 <div> 10 <h1>Search Results for: {query}</h1> 11 </div> 12 ); 13 } 14 15 export default SearchResults; 16
In the above code, useSearchParams is a hook that returns an array. The first element of the array is a URLSearchParams instance, which we can use to get the value of the q query parameter.
The useSearchParams hook makes it easier to work with query params in React Router, and it’s a welcome addition to the library. However, if you’re still using an older version of React Router, you can continue to use the URLSearchParams API directly, or create a custom hook as we discussed in the previous section.
Query params are not just for client-side JavaScript. They are also incredibly useful in server-side rendering (SSR) with React. When you’re doing SSR, you can use query params to pass state from the server to the client.
For instance, if you’re building an e-commerce site and you want to pre-render product pages on the server, you might use a URL like /product?productId=123 to tell the server which product to render. The server can then use the productId query param to fetch the product data from the database and pre-render the product page.
Here’s an example of how you might use query params in SSR with React and Express:
1 import React from 'react'; 2 import ReactDOMServer from 'react-dom/server'; 3 import express from 'express'; 4 import { StaticRouter } from 'react-router-dom'; 5 import App from './App'; 6 7 const server = express(); 8 9 server.get('*', (req, res) => { 10 const context = {}; 11 const app = ReactDOMServer.renderToString( 12 <StaticRouter location={req.url} context={context}> 13 <App /> 14 </StaticRouter> 15 ); 16 17 res.send(` 18 <!DOCTYPE html> 19 <html> 20 <head> 21 <title>My App</title> 22 </head> 23 <body> 24 <div id="root">${app}</div> 25 </body> 26 </html> 27 `); 28 }); 29 30 server.listen(3000); 31
In the above code, we’re using Express to create a server that responds to all GET requests. For each request, we’re rendering the App component to a string using ReactDOMServer.renderToString. We’re passing the current URL (which includes the query string) to the StaticRouter component, which allows the App component and its descendants to access the URL and query params.
In the App component, you can then use the useLocation and useQueryParams hooks to access the query params, just like you would in a client-side React app. This allows you to pre-render pages based on the query params, providing a faster and more SEO-friendly experience for your users.
As we’ve seen, React Router and query params are powerful tools in the toolkit of a front-end developer. They allow us to create dynamic and interactive web applications, passing state through the URL in a way that is both user-friendly and SEO-friendly.
Whether you’re using URL parameters or query strings, React Router provides hooks like useParams and useSearchParams that make it easy to access these values in your components. And with custom hooks, you can encapsulate the logic for parsing query strings, making your component code cleaner and more reusable.
And let’s not forget the role of query params in server-side rendering. By passing state from the server to the client through query params, you can pre-render pages based on dynamic data, providing a faster and more SEO-friendly experience for your users.
So, the next time you’re building a React app, don’t shy away from using React Router and query params. Embrace their power and flexibility, and you’ll be able to build more dynamic and interactive web applications.
And remember, as with any tool or technique in web development, the key to mastering React Router and query params is practice. So, keep coding, keep experimenting, and keep learning. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.