Skip to content
Related Articles

Related Articles

How to get parameter value from query string in ReactJS?
  • Last Updated : 28 Dec, 2020

We can access query string via this.props.location.search then we can parse it using a library called query-string. This library has a parse() function that parses the query string and returns an object.

 For example, the query string is ?site=gfg&subject=react then after parsing object will be:

{
 Site:"gfg",
 Subject:"react"
}

Module Installation: Install the library using the following command:

npm install query-string 

Creating React Application:

Step 1: Create a React application using the following command:



npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Filename: App.js

Javascript




import React, { Component } from "react";
// Importing Module
import queryString from 'query-string'
  
class App extends 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 App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

  • You will see the following button and text on the screen:

  • After clicking on the button, the following will be the output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :