Add Routing for Shopping Cart in React Application – Part 4
Welcome back to our journey of building a Shopping Cart application! In this fourth part, we’re going to level up our app by adding routing. Routing allows us to navigate between different pages or views within our application. It’s like adding signposts to guide our users through their shopping experience. Let’s dive in!
Add Routing for Shopping Cart
1. Install React Router
First things first, let’s install React Router. Run the following command to install react-router-dom npm package.
1 | npm i react-router-dom |
You will find the version of the following packages in React application.
2. Configuring Routes
Next, we need to set up our routes. Update the following files where we’ll define our application routes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import { Route, BrowserRouter, Routes } from "react-router-dom"; import Home from "./containers/Home"; import Products from "./containers/Products"; import Cart from "./containers/Cart"; import Layout from "./components/Layout"; function App() { return ( <BrowserRouter> <Routes> <Route element={<Layout />}> <Route path="/" element={<Home />} /> <Route path="/products" element={<Products />} /> <Route path="/cart" element={<Cart />} /> </Route> </Routes> </BrowserRouter> ); } export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import { Outlet } from "react-router-dom"; import Header from "./Header"; import Footer from "./Footer"; function Layout() { return ( <> <Header /> <hr className="my-2" /> <Outlet /> <hr className="my-2" /> <Footer /> </> ); } export default Layout; |
3. Navigating Between Pages
Now that our routes are set up, we can add navigation links to our components using the Link component from React Router:
1 2 3 4 5 6 7 8 9 10 11 12 | import { Link } from "react-router-dom" function Cart() { return ( <> <h1 className="text-2xl text-blue-700 font-bold">Cart Page!</h1> <Link to="/">Home</Link> </> ) } export default Cart |
1 2 3 4 5 6 7 8 9 10 11 12 | import { Link } from "react-router-dom"; function Home() { return ( <> <h1 className="text-2xl text-blue-700 font-bold">Home Page!</h1> <Link to="/products">Products</Link> </> ); } export default Home; |
1 2 3 4 5 6 7 8 9 10 11 12 | import { Link } from "react-router-dom" function Products() { return ( <> <h1 className="text-2xl text-blue-700 font-bold">Products Page!</h1> <Link to="/cart">Cart</Link> </> ) } export default Products |
Conclusion
Congratulations! You’ve successfully added routing to your Shopping Cart application. With React Router, navigating between pages is a breeze, providing a seamless shopping experience for your users. Keep exploring and building, and remember: the journey of coding is as exciting as the destination!
Happy Coding!
“Life is a journey, not a destination – and so is coding!”