When we were developing the SUSI Web Chat application we wanted to implement set of static pages with the chat application. In the start we just wanted to navigate through different static pages and move back to the web chat application. But it takes time to load a new page when user clicks on a link. Our goal was therefore to minimize the loading time by using lazy loading. For that we used react-route .It is standard library for react js.
From the docs:
“React Router keeps your UI synced with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.” (https://www.npmjs.com/package/react-router-plus)
We need react-route to be installed in our application first. We can install it using NPM by running this command on project folder.
Next we have to set up our routes. We have two types of headers in our application. One is chat application header, second one is static page header. In static page header we have a navigation to switch between static pages.
First we need to choose the router type because there are two types of routers in react. “” and “” we can use “” in our example because our server can handle dynamic requests. If we are requesting data from static page we should use “” .
We used that in “” and made another new component called “” and used it on “index.js” like this.
In “App.js” we can set up routes like this.
We use elements to render component when they match with the corresponding path. We use “path” to add router location that we need to match width the component. We use “exact” property to render the component if location exactly matches with the “path”. If we do not use “exact” property it renders when we have child routes after the path like “/blog/1 “ .
We used “” element to group routes.
We can’t use anchor () tags to navigate pages without reloading. We have to use tags instead of that. We have to replace all the places we have used
<a href= ‘URL’>lable name </a>
<Link to=’URL’>Lable name</Link>
After doing above changes application will perform faster and it will load all page contents soon after you click the navigation links.
If you would like to join with FOSSASIA and contribute to SUSI Web Chat Application please fork this repository on Github.
- React Route v4 tutorial and other options: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf
- React-router-dom node package https://www.npmjs.com/package/react-router-dom