Do you like experiments as we do? We are inviting you to the world of React experiments. How about routing in React with hooks? Are you with us? If so, check this material.
The router module is published on npm and can be installed by calling
npm -i hookrouter. It has zero dependencies and adds about 2.9kb to your bundle.
This is what you have to keep in mind:
- You can define your possible routes as an object with urls as keys and result functions as values. The
useRoutes()hook consumes the routes object, evaluates them one by one and checks if they match the current url path. If one of the routes matches, its function will be called.
- You can also use multiple URL parameters if you want to – just give them different names.
- If you call the next
useRoutes()inside a child component, it will not match against the full url path but only against the part that remains, which would be
/details. You can nest routes as much as you like.
- We perform the redirect before we match any routes to prevent an unnecessary re-render of the
<ProductArea />component. With this approach, other components may just navigate the user to the product area and leave the decision where the user should end up to that component.
Feel free to check the examples here.
You can rely on us and read our article where you can meet React 360 (or React VR). Enjoy!