React Router DOM

·

2 min read

Why Routing ?

  • We have to navigate from one view to another without hitting server as in contrast to MultiPage web App where the page reloads every request to change the view .
  • So here, we have to navigate from one view to another without hitting server. For this React JS provides the react-router-dom library.

components of react router DOM :

Let's discuss how to use these components and their props:

BrowserRouter : It is a primary component containing the entire routing configuration. It is a more popular one because it uses the HTML5 History API to keep track of your router history. All the routes should be wrapped within a container element such as div.

Route : It is a prop of Router. It maps routes to our application’s component hierarchy using "path“ and "component" props and sets all navigational routes

path : Maps to the path given in URL

component : Contains component name to be rendered when the route is mapped

exact :This property tells Route to match the exact path. In the below example Header component will render when the browser's location path matches exactly / .

Link: Create navigational links using "to" prop

Route Parameters:

Parameters passed along with URL are called route parameters.

Ex :

<Route path="/display/:Subject" component={DisplaySub}/>
<Link to="/display/React"> React </Link>

In DisplaySub component, route param can be accessed as follows:

this.props.match.params.Subject

match : react-router-dom passes in a prop called match into every route that is rendered. Inside this match object, we have another object called params.

params : It is an object containing URL parameters


Configuring Routes Programmatically :

  • Components that are passed to the component will get history, location, and match as props.

  • So when we want to navigate from one component to another component, we can achieve it as shown below

this.props.history.push('url')

  • Higher order components are functions which accepts components as an argument and returns a new enhanced component. HOC's helps in reusing the component's logic.

  • const EnhancedComponent = higherOrderComponent(Component); As already mentioned history, location, match are available as props for components which are mentioned with the

  • But if a component is not mentioned to the Route component, the history, location, and match will not be available as props. In that case, we can use withRouter higher order component as shown below.

import { withRouter } from 'react-router';
export default withRouter(component)