The question about getting parameters from the URL address appears on forums for developers very often. In this post, I am going to show you two very simple, yet useful solutions that may be helpful for you. Which one works best for you depends on your specific circumstances.
Plain JavaScript solution
This is the most universal solution. It does not require React Router or even React itself. Thus, it can be used in applications built with other JS frameworks or plain JavaScript. In order to get query parameters from the URL, we can use URLSearchParams. In simple words, URLSearchParams is a defined interface, implemented by modern browsers, that allows us to work with the query string.
//Sample address: http://localhost:3000/?id=55&name=test const queryParams = new URLSearchParams(window.location.search); const id = queryParams.get('id'); const name = queryParams.get('name'); const type = queryParams.get('type'); console.log(id, name, type); // 55 test null
When a parameter you try to get does not exist in the URL address, queryParams.get() method will return null.
All URL parameters are strings. If you need a different type of parameter, e.g. id to be an integer, you need to parse it with a relevant function (parseInt() for the case above).
If you are looking for an example in React JS, take a look on this gist.
However, when you already use React Router in your project, you can take advantage of useLocation() hook (only for functional components) that will return window.location object for you. This solution looks more elegant, but it’s only syntactic sugar. The end result will be exactly the same.
React router solution – parameters in the URL path
This solution will work perfectly for the required parameters. In order to install React Router library, just execute the command below:
npm install react-router-dom
All examples in this post require React Router in version 5 or higher. Some of the functions I used will not work with older versions of the library.
Let’s assume we have only 2 possible pages that can be displayed in our application:
- user profile under /user/<username> URL address, where <username> can be any string
- default page for other URLs
To include a variable into an URL address in React Router, you just need to precede the variable name with a colon. In our case, the path will look like this: /user/:userName.
import React, { Component } from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import User from './User'; class App extends Component { render() { return ( <Router> <Switch> <Route exact path='/user/:userName' component={User} /> <Route> <div>Default page</div> </Route> </Switch> </Router> ); } } export default App;
Now, we can use the userName variable in the User component. How we can access that variable depends on whether it is a functional or class component.
For functional components we can use useParams() hook (introduced in React Router v5, requires also React 16.8 or higher).
// Functional component import React from 'react'; import { useParams } from 'react-router-dom'; const User = () => { const { userName } = useParams(); return ( <div>Username: { userName }</div> ); } export default User;
For class component we can just get our parameter from props object.
// Class component import React, { Component } from 'react'; class User extends Component { render() { const { userName } = this.props.match.params; return ( <div>Username: { userName }</div> ); } } export default User;
Conclusion
The two solutions I presented are sufficient for most cases I can imagine. However, if you need some additional features, like validation or parsing boolean type parameters, you can also use one of the open-source libraries like qs, querystring, url-parse, and many more that provide more advanced features.
Thanks for your article. Very easy way to understand the concept.
You may need to add withRouter() to your class component
This part seems not working
const { userName } = useParams();
says property userName does not exist on type {}