Routing using React Router

How to Install React Route :  npm install react-router-dom --save

1. Web Apps

Web Apps are of two types, based on how we get content:

  • Multi-page application (MPA)
  • Single-page application (SPA)

1.1 Multi-page application (MPA)

  • Every URL is associated with corresponding resources (HTML, CSS, JS).
  • The browser downloads these resources when you access them or navigate between URLs.

1.2 Single-page application (SPA)

  • All URLs are associated with a single HTML page.
  • On navigating we only get the additional content (Component - HTML, CSS, JS).

1.2.1 Advantages of using Single-page application (SPA)

  • Faster Page loading - since they load only necessary Component (HTML, CSS, JS) resources on subsequent requests.
  • React is mainly used to build Single-page applications.

2. React Router

In React, we build Single-page applications using React Router.

To implement routing, React Router provides various components:

  • BrowserRouter
  • Link
  • Route
  • Switch

2.1 BrowserRouter

To add routing wrap all the Components with

BrowserRouter
.

Syntax:

<BrowserRouter>
<Component 1>
<Component 2>
...
</BrowserRouter>
JSX

Link
Component creates hyperlinks that allows to navigate around in application.

Syntax:

<Link to="Path"> Display Text</Link>
JSX

The

to
prop specifies absolute path.

2.3 Route

The

Route
component renders specific UI component when path matches current URL.

<Route path="Path" component={Component} />
JSX

2.3.1 Exact

Renders the route if path matches exactly the current url

<Route exact path="Path1" component={Component1} />
JSX
Note
If user enters undefined Path, the Component won’t be rendered

2.3 Switch

The

Switch
component will only render the first route that matches the path. If no path matches, it renders the Not Found component.

<Switch>
  <Route path="Path1" component={Component1} />
  <Route path="Path2" component={Component2} />
 <Route component={NotFound} />
</Switch>
Watch Full Code : https://github.com/codingkey-cmd/react-rutes-part1-example.git

00000000000

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form