To extract query string parameters from a URL in React, In this tutorial, you will learn how to get parameter values from the query string in React JS applications.
A query string is part of a URL containing additional information about the requested resource. Query strings start with a question mark (?) followed by a list of key-value pairs separated by ampersands (&).
For example, consider the following URL:
https://example.com/search?q=react+js&page=1
In this URL, the query string is “q=react+js&page=1”. It contains two key-value pairs: “q=react+js” and “page=1”. The key “q” has a value of “react+js”, and the key “page” has a value of “1”.
How to Get Parameter Value From Query String in React JS
Steps to get url parameter values without react-router:
Step 1 – Create React App
Run the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To start the React app, use the following command:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install Query String and Bootstrap Package
Run the following commands to install query string and boostrap library into your react app:
npm install bootstrap --save npm install query-string
Import react router and bootstrap.min.css file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
function App() {
return (
<div>
<h2>How to Get Parameter in URL in React js with Router</h2>
</div>
);
}
export default App;
Step 3 – Create Home Component
Create home component named Home.js
in src
directory:
import React from 'react'
import queryString from 'query-string'
class Home extends React.Component{
state = {
site: 'unknown',
subject: 'i dont know'
}
handleQueryString = () => {
// Parsing the query string
// Using parse method
let queries = queryString.parse(this.props.location.search)
console.log(queries)
this.setState(queries)
}
render() {
return (
<div style={{ margin: 200 }}>
<p> WebSite: {this.state.site} </p>
<p> Subject: {this.state.subject} </p>
<button
onClick={this.handleQueryString}
className='btn btn-primary'>
click me </button>
</div>
);
}
}
export default Home;
Let’s assume you have the following URL “http://localhost:3000/?site=tutsmake&subject=get-query-string
” that can be displayed on browser, and get query string from it by clicking the button given on the page.
Step 4 – Import Component in App.js
Import Home.js file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
iimport queryString from 'query-string'
import Home from './Home'
function App() {
return (
<div className="App">
<Home />
</div>
);
}
export default App;
Conclusion
In this article, you have learned how to get parameter value from query string in React JS using the built-in “URLSearchParams” API.