I
I
IDDH2016-01-27 10:51:24
React
IDDH, 2016-01-27 10:51:24

React js. How to get a parameter from a nested route?

There is react-router (react-router 2.*):

<Router  history={hashHistory}>
    <Route path="/" component={App}>
        <Route path="list/:id" component={List} />
        <Route path="another/:id" component={Another} />
    </Route>
</Router>

How to get the :id property of the {List} nested route in the {App} component?
And how can I differentiate between {List} and {Another} components in {App}?
In the {App} component, rendering takes place as follows. way:
<div className="wrapper">
    <MenuList />
    {this.props.children}
</div>

The meaning is as follows:
I need to perform some action with the id in the MenuList, for example, set the active state of the item.
How to do it most correctly and in React style?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman_Kh, 2016-01-27
@Roman_Kh

Add a getId() function to the List component, which will return this.props.params.id
. And in the App, you can add a function that will return all ids of all children.
A reference to the function can be passed as a parameter when creating the MenuList component.
And the MenuList will call it on rendering and parse which items to make active and which not.
Alternatively, you can make a store (see Flux ) that will contain data about the rendered components. And then everyone (App, MenuList, List) will communicate only with this store.

V
vilix, 2016-01-27
@vilix

If I understand part of your question correctly, in App you can get the :id of child components like this:

if (this.props.children)
      console.log(this.props.children.props.params.id);

i.e. for example, you followed the link /list/11 then the code above will display "11"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question