Dynamic parameters with patterns

Trying to set up a responsive application using React-Router v4. I need navigation with a dynamic route parameter and the ability to target areas of my application template using a component that accepts a dynamic route parameter. According to the v4 docs, I need to define my routes as follows:

const routes = [ { exact: true, path: '/vpcs', navLevel2: () => <VpcList></VpcList>, mainContent: () => <h1>Hello VPCs</h1> }, { exact: true, path: '/vpcs/:vpcName', navLevel2: () => <VpcList></VpcList>, mainContent: () => <Vpc></Vpc> } ] 

Then I can do:

 <BrowserRouter basename="/"> <div> <nav> <ul> <li><NavLink to="/vpcs">Vpcs</NavLink></li> </ul> </nav> <nav> {routes.map((route, index) => ( <Route key={index} path={route.path} exact={route.exact} component={route.navLevel2} /> ))} </nav> <main> {routes.map((route, index) => ( <Route key={index} path={route.path} exact={route.exact} component={route.mainContent} /> ))} </main> </div> </BrowserRouter> 

However, there seems to be no way to pass the value for :vpcName component that requires it. When I find the console logs /vpc/my-vpc-name route

 Uncaught TypeError: Cannot read property 'params' of undefined at new Vpc ... 

To find out what I should work with, instead of component={route.mainContent} I tried:

 component={() => (<p>{JSON.stringify(arguments)}</p>)} 

And it gave

 {"0":{"i":480,"l":false,"exports":{}},"1":{}} 

... which is not encouraging.

What should I do? Do I need to rewind in v3 to get the template areas to work with dynamic route parameters?

0
reactjs react-router-v4
Nov 12 '17 at 23:58
source share
2 answers

Your component actually receives the parameters through the details, you just do not use them. Try to do something like: mainContent: props => <div>{props.match.params.vpcName}</div>

I made a small example for you here: https://codesandbox.io/s/v61p95k850

+2
Nov 13 '17 at 0:47
source share

Instead of using component in the <Route> you should use render , which takes this function, and then you can use your function, for example {() => (<p>{JSON.stringify(arguments)}</p>)} inside her.

Here is a link to their document

0
Nov 13 '17 at 0:05
source share



All Articles