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
- React Router Dom – Webpage : https://reactrouter.com/web/guides/quick-start
- React Router Dom – NPM page : https://www.npmjs.com/package/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 = /
Cart Page => path = /cart