React-router: Why can the Router only have one child?

Created on 9 Nov 2017  路  3Comments  路  Source: ReactTraining/react-router

Well, basically - why is there a limit on <Router /> having a single child?

I tried looking at the code, but I couldn't really make sense of the why:

https://github.com/ReactTraining/react-router/blob/7cda4bda61dd039ee0de51841c3a64dd486c2ff8/packages/react-router/modules/Router.js#L54

Thanks for a great library by the way - I just want to understand why stuff is like it is.

Most helpful comment

Because <Router> belongs at the top of the component tree, near your ReactDOM.render. And because it just returns its children when rendering, that will go straight to up to the top. So, this:

ReactDOM.render(
  <Router>
    <div />
    <div />
  </Router>
)

is basically this:

ReactDOM.render(
  <div />
  <div />
)

And that's not valid input for render.

So, we use React.Children.only to ensure we only have one child (That's the main use case for that function) and yell at you if you try to have more. Sorry for the yelling, but it's for everyone's benefit.

All 3 comments

Because <Router> belongs at the top of the component tree, near your ReactDOM.render. And because it just returns its children when rendering, that will go straight to up to the top. So, this:

ReactDOM.render(
  <Router>
    <div />
    <div />
  </Router>
)

is basically this:

ReactDOM.render(
  <div />
  <div />
)

And that's not valid input for render.

So, we use React.Children.only to ensure we only have one child (That's the main use case for that function) and yell at you if you try to have more. Sorry for the yelling, but it's for everyone's benefit.

Ah that鈥檚 why! Thanks a ton for taking the time to explain it to me :-)

Also @selbekk thanks for asking it - had the same question myself & was nice to see it explained clearly here. Thanks for the clear response @timdorr!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

andrewpillar picture andrewpillar  路  3Comments

jzimmek picture jzimmek  路  3Comments

ryansobol picture ryansobol  路  3Comments

davetgreen picture davetgreen  路  3Comments

nicolashery picture nicolashery  路  3Comments