0

I have this simple enough React app (created with create-react-app 1.5.2, and fluff removed). It has by default installed react-router 4.2.0.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route } from 'react-router';
import history from 'history/createBrowserHistory';

const App = ({
    params
}) => (
    <div>
        We are here: {params.filter}
    </div>
);

const Root = () => (
    <Router history={history()}>
        <Route path="/:filter?" component={App} />
    </Router>
);

ReactDOM.render(<Root />, document.getElementById('root'));

I am using the syntax described in following answer to create an optional path parameter: https://stackoverflow.com/a/40872420/1461424

However, this renders the error: TypeError: Cannot read property 'filter' of undefined at:

         <p>We are here: {params.filter}</p>

Using old style /(:filter) renders a blank page. So is (/:filter).

I have read a number of similar questions, but none matched my issue. So my question is: How can I declare an optional path parameter inside my Root component, and then read the parameter from my App component?

sampathsris
  • 21,564
  • 12
  • 71
  • 98

1 Answers1

2

I think that in React Router v4 you should use a different prop, match:

const App = ({
    match
}) => (

which will then contain params:

    <p>We are here: {match.params.filter}</p>
sampathsris
  • 21,564
  • 12
  • 71
  • 98
César Landesa
  • 2,626
  • 1
  • 13
  • 18