Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to get parameter value from query string in ReactJS?

How to get parameter value from query string in ReactJS?

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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments