uekyo
uekyo

Reputation: 431

No get query sting data in react

I'm trying to get query string parameters tho, it's blank. This is URL.

https://master.deeiswmgeowge.amplifyapp.com/?site=gfg&subject=react

Then, this.props is empty.

The below is the source.

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 
    console.log(`this.props`, this.props)
    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;
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "query-string": "^6.14.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.2",
    "web-vitals": "^1.0.1"
  },

This is the error image.

enter image description here

Upvotes: 1

Views: 400

Answers (2)

Bourbia Brahim
Bourbia Brahim

Reputation: 14712

You're not using react router , thus no location parameter in props :

so you have two solution ,

  • 1 whether adding react-router-dom and wrap your app with router , ( or using with router hook like export default withRouter(App))

  • 2 or access directly window.location.search and get params with URLSearchParams

by example :

const urlParams = new URLSearchParams(window.location.search);
const site = urlParams.get('site');
const subject = urlParams.get('subject');

Upvotes: 2

sankha banerjee
sankha banerjee

Reputation: 11

Need to pass the props like

onClick={()=>  this.handleQueryString(this.props)} 

and received like

handleQueryString(arg) {
....
}

Upvotes: 1

Related Questions