cft
Become a CreatorSign inGet Started

Introducing Hook Router: a New Routing Library for React

React.js does not support routing out of the box. React Router is one of the very popular library that is used with React.js to enable routing.


user

Bewar Salah

4 months ago | 4 min read
Follow

introducing-hook-router-new-routing-library-glbqz

Introduction

React.js does not support routing out of the box. React Router is one of the very popular library that is used with React.js to enable routing.

Hook Router is a new library for enabling routing in react.js. It is built around react hooks. It is very simple and small. It comes with a simple and neat documentation. A new fresh react developer can easily get hands dirty with it.

In this lesson I dive into react routing using hookrouter.js . We are going to create some routing with some navigation links.

Overview

An example is easier to understand. I try to make it simple for sake of easy understanding. We demo a react application that consists of four routes: homeaboutusers and user-detail. We also demonstrate dynamic routing in users and user-detail pages.

Let us create a react.js app using the popular command line npx, and install hookrouter.

npx create-react-app routing-demo

cd routing-demo

npm i -S hookrouter

We create the bellow components inside the src folder:

  1. Menu: holds the list of menus and used
  2. Home: is the home page.
  3. About: is the about page.
  4. Users: displays a list of users which is read from an API.
  5. UserDetail: displays the details of a single user and it is read from an API.
  6. NotFound: is a page the application goes to when there url does not match any routes.

/components/Menu.js

/pages/Home.js

/pages/About.js

/pages/NotFound.js

/pages/Users.js

/pages/UserDetail.js

We remove the bellow files inside the src folder:

logo.svg

App.test.js

App.css

We also need to remove react’s strict mode inside the index.js otherwise the clicking on the <A href="/about" />link wont redirects to about page.

Routing

We define the routes as a plain javascript object. Each property name is the route URL and the value is the react component (in our case the routes: home and about).

const routes = {

"/": () => <Home />,

"/about": () => <About />,

};

Inside the App component, we pass the routes to useRouter() hook from reactrouter library to register the routes with their corresponding component.

We return a match ed route otherwise NotFound page from the App component as follows: { match || <NotFound /> } .

import { useRoutes } from "hookrouter";

const routes = {...};

function App() {

const match = useRoutes(routes);

return (

<div className="App">

<Menu />

<div className="container">

{match || <NotFound />}

</div>

</div>

);}

Links

Links is used to navigate between pages. Inside the menu component, we define the links. The link is defined using A component from hookrouter library.

import { A } from "hookrouter";

const Menu = () => {

return (

<nav className="App-Header">

<A href="/">Home</A>

<A href="/about">About</A>

</nav>

);

};

Dynamic Routes

One of the most important features of routing is to handle dynamic routing. Sometimes we need to have a dynamic value in the URL such us an ID and based on that we fetch data from server or display some information.

We demonstrate this feature by example. We show a list of users which fetched from a backend server. We also, add a button for each user to display the user’s detailed information. In the link we should have a dynamic value such as ID to know which user to display.

In the routes, parameters are defined by adding a colon : in the beginning of the URL part.

  1. Add two extra routes: /users and /users/:id/detail .
  2. Add two components: Users and UserDetail .
  3. Pass id as parameter in UserDetail route.

const routes = {

.....

"/users": () => <Users />,

"/users/:id/detail": ({ id }) => <UserDetail id={id} />,

};

Users Page

Users page displays a list of users which is read from {JSON} Placeholder. There is a link for each user which points to user details and the URL contains the ID of the user.

import { A } from "hookrouter";const Users = () => {

const [users, setUsers] = useState([]); useEffect(() => {

fetch("https://jsonplaceholder.typicode.com/users")

.then((res) => res.json())

.then((result) => setUsers(result));

}, []); return (

<table id="users">

<thead>

<tr>

<th>#</th>

<th>Name</th>

<th></th>

</tr>

</thead>

<tbody>

{users.map((user) => (

<tr key={user.id}>

<td>{user.id}</td>

<td>{user.name}</td>

<td>

<A href={`/users/${user.id}/detail`}>Details</A>

</td>

</tr>

))}

</tbody>

</table>

);

};

User Detail Page

The ID of user is passed to user detail page. The ID is used to fetch the user detail information from the backend server: {JSON} Placeholder.

const UserDetail = (

{ id }

) => {

const [user, setUser] = useState({}); useEffect(() => {

fetch(`

https://jsonplaceholder.typicode.com/users/${id}

`)

.then((res) => res.json())

.then((result) => setUser(result))

}, [id]); return (

<div>

<h3>User Detail:</h3>

<p>ID: {user.id}</p>

<p>Name: {user.name}</p>

<p>Username: {user.username}</p>

<p>Phone: {user.phone}</p>

<p>Email: {user.email}</p>

<p>Company: {user.company?.name}</p>

</div>

);

};

Conclusion

Enabling routing in react.js application is very easy with hookrouter. I tried to cover the basics of the routing but there are still more features of the library which are not covered like redirecting and programmatic navigation.

For the complete source code, please visit this git repository.

Upvote


user
Created by

Bewar Salah

Follow

Software Developer


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles