Getting Started with React Router

Routing concept is very importance in almost every web application’s architecture, which could not be left out in the React. Power of routing enables us to make a full fleshed single page applications with React. We can make use of React-Router for Routing in React.

Setup and Installation

We need:

  • Node.js  and npm.
  • create  a new project.

React Router is mainly composed of these packages: react-routerreact-router-dom, and react-router-native.

Create a new project with create_react_app and navigate to the directory created as shown below:

Install react-router-dom

There are two types of Router that you can use in your React  application. The BrowserRouter and HashRouter. You have seen that many url was previously containing  # which is not being used now a days. So to acheive that, we use HashRouter  where the url before #indicates the server address and after hash the url is managed by react router . But now a days we see url without for that we can use  BrowserRouter  .

Index.js

In the code above, I imported the BrowserRouterRoute from react-router-dom. And I wrapped the <App/> component with Router which is the alias of BrowserRouter. The Router component is the first step to routing successfully. The Router component can only have one child element or component. So, in this way we wil[l define the routes.

app.js

In the code above, we have links that should direct the user to //languages, and /cities using the <Link> component.

Home

 

Component should be rendered only on the /, root route. However, it is rendered on all the routes. The / matches /airportsand /cities routes, therefore rendering its component in these two other routes. The solution to this is to simply add the exact prop to the / route.

Leave a Reply