Ilja Ilja - 1 month ago 10
React JSX Question

Why do we need a "root" scene in react native router flux

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.

Answer

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}/>
  }
}
Comments