Routing anywhere using react-router 🛣

Yannick S
1 min readFeb 27, 2018

Hi Jared!

For the routing part, I’m using react-router.

react-router has support for react web (with react-router-dom) and react native (with react-router-native).

So I installed both packages and created platform specific files to export the react-router dependency like so :

  • Routing.native.js
export {
NativeRouter as Router, // Rename
Switch,
Route,
Link
} from 'react-router-native'
  • Routing.web.js
export {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'

then in my app I can import my ./Routing file (you must import the file without its extension) and both platforms will receive the dependency they need because the packagers will resolve the right extension ( *.web.js for Create React App and *.native.js for Create React Native App)

import { Router, Switch, Route, Link } from './Routing'const App = () => (
<Router>
<Switch>
<Route exact path="/" component={HomeComponent} />
<Route path="/one" component={OtherComponent} />
</Switch>
</Router>
)

Here is the full example :

import React from 'react'
import { View } from 'react-native'
import { Router, Switch, Route, Link } from './Routing'
const HomeComponent = () => (
<View>
<Text>Home page</Text>
<Link to="/other">
<Text>Click to go to another page</Text>
</Link>
</View>
)
const OtherComponent = () => (
<View>
<Text>Another page!</Text>
<Link to="/">
<Text>Take me back to the home page</Text>
</Link>
</View>
)
const App = () => (
<Router>
<Switch>
<Route exact path="/" component={HomeComponent} />
<Route path="/one" component={OtherComponent} />
</Switch>
</Router>
)

--

--

Yannick S

Software Engineer • I make software tings💡