The first step when implementing routing is to install the navi and react-navi libraries. Then, we define the routes. Follow the given steps to do so:
- First, we have to install the libraries using npm:
> npm install --save navi react-navi
- Then, in src/App.js, we import the Router and View components and the mount and route functions from the Navi library:
import { Router, View } from 'react-navi'
import { mount, route } from 'navi'
- Make sure that the HomePage component is imported:
import HomePage from './pages/HomePage'
- Now, we can define the routes object using the mount function:
const routes = mount({
- In this function, we define our routes, starting with the main route:
'/': route({ view: <HomePage /> }),
- Next, we define the route for a single post, here we use URL parameters (:id), and a function to dynamically create the view:
'/view/:id': route(req => {
return { view: <PostPage id={req.params.id} /> }
}),
})
- Finally, we wrap our rendered code with the <Router> component, and replace the <PostPage> component with the <View> component in order to dynamically render the current page:
<Router routes={routes}>
<div style={{ padding: 8 }}>
<HeaderBar setTheme={setTheme} />
<hr />
<View />
</div>
</Router>
Now, if we go to http://localhost:3000, we can see a list of all posts, and when we go to http://localhost:3000/view/react-hooks, we can see a single post: the React Hooks post.