Search code examples
react-nativeexponentjs

ExNavigation : how to pass props to all router components?


In the following code, what's the best way to pass the database variable as props to all the components served by the Router/NavigationProvider?

import {
  createRouter,
  NavigationProvider,
  StackNavigation,
} from '@exponent/ex-navigation'

const Router = createRouter(() => ({
  jobs: () => Jobs,
  sample: () => Sample
}))

render () {
  const database = this.openDatabase()
  <NavigationProvider router={Router}>
        <StackNavigation initialRoute={Router.getRoute('home')} />
  </NavigationProvider>
}

Thanks!


Solution

  • You should create a new javascript file which exports your database connection and import it in your component you wish to use it.

    You can also create higher order component which gives database connection as a prop to your component. This is similar to withNavigation which is built-in in ExNavigation or connect which comes with Redux's React bindings.

    However, since HOC is a bit advanced topic (but not hard to grasp!) here is an example without it.

    services/database.js

    // Open database connection here and export it like any other module.
    // The following is pseudo code to illustrate example
    
    import { database } from 'database'
    export default database.connect()
    

    routes.js

    import Jobs from './containers/Jobs'
    import Sample from './containers/Sample'
    import { createRouter } from '@exponent/ex-navigation'
    
    const Router = createRouter(() => ({
      jobs: () => Jobs,
      sample: () => Sample
    }))
    
    export default Router
    

    App.js

    import React from 'react'
    import {
      NavigationProvider,
      StackNavigation,
    } from '@exponent/ex-navigation'
    
    const App = () => (
      <NavigationProvider router={Router}>
         <StackNavigation initialRoute={Router.getRoute('home')} />
      </NavigationProvider>
    )
    
    export default App
    

    containers/Jobs.js

    import React, { Component } from 'react'
    
    // Import database connection in every container component you wish to use it
    import databaseConnection from '../services/database'
    
    export default class Jobs extends Component {
      state = {
        jobs: []
      }
    
      componentDidMount() {
        databaseConnection
          .get('jobs')
          .then(jobs => this.setState({ jobs }))
      }
    
      render() {
        return (
          {this.state.jobs.map(job =>
            // Render jobs
          )}
        )
      }
    }