John Livermore
John Livermore

Reputation: 31313

Gain access to query parameters via React

I have seen several posts that say you should reference this.props.location to gain access to the query string parameters. However, whereever I check this property, location is always 'undefined'. I am missing something obviously.

Here is my setup...

package.json

{
  "name": "Lender.Services.Web",
  "homepage": "/dataexchange/lender",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^3.3.7",
    "react": "^16.0.0",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.0.0",
    "react-grid-system": "^4.1.1",
    "react-router-bootstrap": "^0.24.4",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.17",
    "rimraf": "^2.6.2"
  },
  "scripts": {
    "start": "rimraf ./build && react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

index.js

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');

ReactDOM.render(
  <BrowserRouter basename={baseUrl}>
    <App />
  </BrowserRouter>,
  rootElement);

registerServiceWorker();

App.js

import React, { Component } from 'react';
import { NewRequest } from './components/NewRequest';

export default class App extends Component {
    displayName = App.name

    render() {
        return (
            <NewRequest />
        );
    }
}

If I break in App.js in the render function, the this.props.location is undefined.

How do I gain access to the query string parameters with my setup?

Upvotes: 1

Views: 190

Answers (1)

Chaim Friedman
Chaim Friedman

Reputation: 6253

React router only injects the route props to components it routed to. Now your App component is not getting routed to via react router, it simply getting rendered as the top level component.

<BrowserRouter basename={baseUrl}>
    <App />
 </BrowserRouter>,

If you want react-router to inject the route params, you need to actually have a route which leads to the App component. Something like this.

<BrowserRouter basename={baseUrl}>
    <Route path={"/"} exact component={App} />
 </BrowserRouter>,

Now when you go the / route in the browser you will see App, but if you go elsewhere you will not, this is because now react-router is rendering your component when the path matches, and when it renders it, it will also inject the route props to it.

Upvotes: 2

Related Questions