4

I am implementing a routing library for my app, one that seems to be really good is react-native-router-flux they have good docs and implementation, I just have one question.

In all their examples, scenes are wrapped in a root scene, so:

<Scene key="root">
  <Scene key="sceneOne" component={SceneOne} />
  <Scene key="sceneOne" component={SceneTwo} />
</Scene>

I have tried using it without root scene and it still works as expected:

<Scene key="sceneOne" component={SceneOne} />
<Scene key="sceneOne" component={SceneTwo} />

Hence my question, as I currently don't understand purpose of the root.

Ilja
  • 44,142
  • 92
  • 275
  • 498

1 Answers1

4

If you're creating your scenes simply by adding them under your <Router> element, then you don't necessarily need a root element. For example, the following would work:

  render() {
    return <Router>
        <Scene key="login" component={Login} title="Login"/>
        <Scene key="register" component={Register} title="Register"/>
        <Scene key="home" component={Home}/>
    </Router>
  }

However, if you're creating your scenes using Actions.create() then you need a root element because adjacent JSX elements must be wrapped in an enclosing tag. For example (taken by the library's doc):

import {Actions, Scene, Router} from 'react-native-router-flux';

const scenes = Actions.create(
  <Scene key="root">
    <Scene key="login" component={Login} title="Login"/>
    <Scene key="register" component={Register} title="Register"/>
    <Scene key="home" component={Home}/>
  </Scene>
);

/* ... */

class App extends React.Component {
  render() {
    return <Router scenes={scenes}/>
  }
}
Georgios
  • 4,764
  • 35
  • 48
  • is there any other reasons? – Muhaimin Oct 25 '16 at 05:20
  • There can be several other good reasons for doing this but it would depend on the situation. For example, one reason to have a root element is to add props that should be the same for all underlining children, eg set a common style for the NavBar using the `navigationBarStyle` prop. – Georgios Oct 25 '16 at 11:34
  • 1
    your first solution with mutiple Scenes in the Router does not work anymore. The Router should contain only one Scene. – Flosut Mözil Aug 05 '17 at 09:06