Routing in React – react-router-dom

Routing in our React app can be easily implemented with the help of the react-router-dom package. Routing basically changes the components of the webpage based on the URL. Simply the webpage updates with new components without changing the page.

For example, in an e-commerce website made with React, we can switch to pages like home, cart, payment, etc using the routes.

Install react-router-dom – Terminal command

npm install react-router-dom

Routing Example Code using eact-router-dom

import "./App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Header from "./components/header/Header";
import { Home } from "./components/Home/Home";
import { Cart } from "./components/cart/Cart";

function App() {
  return (
    <Router>
      <Header />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/cart" component={Cart} />
      </Switch>
    </Router>
  );
}

export default App;

In the above example, our web app has a Header component constant for all pages, the below component is changing. So the components inside <Switch> are the dynamic components updating based on the URL.

Homepage => path = /

Routing in React - react-router-dom

Cart Page => path = /cart

Routing in React - react-router-dom

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *