0

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;

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 />
  );
};

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.