John
John

Reputation: 41

Read URL parameters

I have a very basic app and I want to read the request parameter values

http://localhost:3000/submission?issueId=1410&score=3

Page:

const Submission = () => {
    console.log(this.props.location); // error

    return ();
}

export default Submission;

App

const App = () => (
   <Router>
       <div className='App'>
           <Switch>
               <Route path="/" exact component={Dashboard} />
               <Route path="/submission" component={Submission} />
               <Route path="/test" component={Test} />
           </Switch>
       </div>
   </Router>
);

export default App;

Upvotes: 0

Views: 68

Answers (3)

Marios Simou
Marios Simou

Reputation: 181

The location API provides a search property that allows to get the query parameters of a URL. This can be easily done using the URLSearchParams object. For example, if the url of your page http://localhost:3000/submission?issueId=1410&score=3 the code will look like:

const searchParams = location.search // location object provided by react-router-dom 
const params = new URLSearchParams(searchParams)
const score = params.get('score') // 3
const issueId = params.get('issueId') // 1410

Upvotes: 0

Lo&#239;ck M
Lo&#239;ck M

Reputation: 358

Did you setup correctly react-router-dom with the HOC in your Submission component ?

Example :

import { withRouter } from 'react-router-dom'

const Submission = ({ history, location }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Submission)

If you already did that you can access the params like that :

const queryString = require('query-string');

const parsed = queryString.parse(props.location.search);

You can also use new URLSearchParams if you want something native and it works for your needs

const params = new URLSearchParams(props.location.search);
const foo = params.get('foo'); // bar

Be careful, i noticed that you have a functional component and you try to access the props with this.props. It's only for class component.

Upvotes: 1

Matthias Fischer
Matthias Fischer

Reputation: 1006

When you use a functional component you will need the props as a parameter of the function declaration. Then the props should be used within this function without this.

const Submission = (props) => {
  console.log(props.location); 
  return (
    <div />
  );
};

Upvotes: 0

Related Questions