7

I'm trying to pass parameter inside my URL, but I have a problem with reading. I'm using react-router v4.

URL: http://localhost:3000/reset?token=123 I'm trying to read it this way:

<Route
   path="/reset?token=:token"
   component={Reset}/>

But this prints empty object console.log(this.props.match.params);. What is strange I have tried to change question mark to other character and looks like it solves my problem, but I would like to keep question mark anyway.

URL: http://localhost:3000/reset_token=123

<Route
   path="/reset_token=:token"
   component={Reset}/>

This already works console.log(this.props.match.params);. Any idea how to make question mark works also correct? Really important to me is to keep using just react-router without any external libs.

Cheers, Daniel

rahul singh Chauhan
  • 323
  • 1
  • 4
  • 15
Dan Zawadzki
  • 682
  • 2
  • 8
  • 28
  • Possible duplicate of [How to get query parameters in react-router v4](https://stackoverflow.com/questions/43216569/how-to-get-query-parameters-in-react-router-v4) – Mayank Shukla Aug 17 '17 at 09:39
  • 1
    @MayankShukla It's similar but i would like to stay just with react-router without any external lib. – Dan Zawadzki Aug 17 '17 at 09:41
  • 1
    in that case you can use `this.props.location.search` then split the values to get different query parameters. – Mayank Shukla Aug 17 '17 at 09:43
  • 1
    @MayankShukla Thanks! Looks like you solve my problem. Best way to solve it and keep using only react-router is `this.props.location.search.split("=")[1]` – Dan Zawadzki Aug 17 '17 at 09:49

4 Answers4

2

How did I solved this issue.

http://localhost:3000?token=mypetismissing

export default function ({ location }) {
  const urlParams = new URLSearchParams(location.search);
  const token = urlParams.get('token');
  console.log(myParams)

  return (
    <div>
      {token}
    </div>
  )
}
U.A
  • 2,991
  • 3
  • 24
  • 36
  • works well. however, when used its important to consider browser's support for it https://caniuse.com/urlsearchparams – Ben Yitzhaki Apr 25 '21 at 11:35
1

You need query-string

Example: http://yoursite.com/page?search=hello

const queryString = require('query-string')

class ProductsPage extends React.Component {
  componentDidMount() {
    let search = queryString.parse(this.props.location.search).search
    console.log(search) // ==> hello
  }

...
}
Alan
  • 9,167
  • 4
  • 52
  • 70
1

Change your path to '/reset'. That'll get the page to render with the token still in the url and you'll be able to grab that token. Happy coding :)

<Route
path="/reset"
component={Reset}/>
1

Extracting Query Parameters from react router path

URL: http://localhost:3000/reset?token=123

First import useLocation from 'react-router-dom

And do this inside your functional component

const { search } = useLocation();

const parameters = new URLSearchParams(search);

const token = parameters.get('token');

Zahir Masoodi
  • 546
  • 7
  • 23