1

I am try to get a query string from a URL but am getting an error. I am using a reactjs project created with Shopify-CLI. I have tried the examples on https://ui.dev/react-router-v4-query-strings/ https://ui.dev/react-router-v5-query-strings/

TypeError: Cannot read property 'params' of undefined

import React, { Component } from "react";

class Users extends Component {
  render() {
const { id } = this.props.match.params;

return (
  <div>
    <h1>User id is {id}</h1>
  </div>
);
}  
}

export default Users;
Tiber
  • 116
  • 1
  • 18

2 Answers2

0

You need to install query-string package npm install query-string

 import queryString from 'query-string';

    console.log(location.search);
    // Output: '?id=1&name=abc'

    const parsed = queryString.parse(location.search);
    console.log(parsed);
    // Output: {id: "1", name: "abc"}

    console.log(location.hash);
    // Output: '#id=1&name=abc'

For different approach you can look: React - How to get parameter value from query string?

Moreover, as your error shows props is undefined. If you are already parsing and getting the values in props from parent component then try logging the props value. Else you can directly use query-string.

const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123
   
Ayushi Keshri
  • 680
  • 7
  • 18
0

try this:

function getUrlVars() {

   let vars = {};
   let parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
   });

   return vars;
}

use it :

let number = getUrlVars()["x"];
let mytext = getUrlVars()["text"];

source: https://html-online.com/articles/get-url-parameters-javascript/