0

Say, I have the following wrapper:

<Switch>
<Route path={`/app/list`} component={ListPage} key="list"/>
<Route path={`/app/view`} component={EditPage} key="view"/>
<Route path={`/app/edit`} component={EditPage} key="edit"/>
<Route path={`/app/new`} component={EditPage} key="new"/>
 </Switch> 

When I load the corresponding component, say ListPage, I want to be able to get the key of the current route, in this case, it would be "list".

If I check this.props.match, I have only isExact, params, path, url but not the key.

mimic
  • 4,897
  • 7
  • 54
  • 93

2 Answers2

1

It's reserved property used in react or react-router internally

If you want to get list use different property. ref, key are reserved

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • But how I would pass any other property? If I just add it into the route object, it's not working. – mimic Dec 01 '20 at 23:33
1

You don't get the key property because you just provide the component that you want to get rendered by the Router to the Route component and this way you cannot specify what props your component will accept except the default ones - match, location, history. You can read more about it here.

You can use the render prop in order to specify how to render the component by providing a render function and this way you can specify the props that your component will accept for example - key. The function will have all the default props provided by the router and you can just spread them as props on your component.

Since key and ref are reserved props in React and they are not passed to the component, I've renamed the key prop to keyName. More info can be found here.

It will look like:

<Switch>
  <Route path="/app/list" render={(props) => <ListPage {...props} keyName="list"/>} />
  <Route path="/app/view" render={(props) => <EditPage {...props} keyName="list"/>}/>
  <Route path="/app/edit" render={(props) => <EditPage {...props} keyName="edit"/>} />
  <Route path="/app/new" render={(props) => <EditPage {...props} keyName="new" />}/>
</Switch> 

and you will be able to access the key by using props.key inside the component that is rendered.

Of course it would be better to extract the render function into a function called renderWithKey or something in order remove the duplication so the code to be cleaner.

user1
  • 1,035
  • 1
  • 9
  • 17