Defining routes

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:

  1. First, we have to install the libraries using npm:
> npm install --save navi react-navi
  1. 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'
  1. Make sure that the HomePage component is imported:
import HomePage from './pages/HomePage'
  1. Now, we can define the routes object using the mount function:
const routes = mount({
  1. In this function, we define our routes, starting with the main route:
    '/': route({ view: <HomePage /> }),
  1. 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} /> }
}),
})
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.252.8