How to do routing in React App using react-router-dom. Creating pages and routing in react js example using react-router.
npm i react-router-dom
import { BrowserRouter } from "react-router-dom";
<BrowserRouter> <App /> </BrowserRouter>
main.tsx
import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import "bootstrap/dist/css/bootstrap.min.css"; import { BrowserRouter } from "react-router-dom"; ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode> );
app.tsx
import Home from "./pages/Home"; import { Container } from "react-bootstrap"; import { Route, Routes } from "react-router-dom"; import Store from "./pages/Store"; import About from "./pages/About"; function App() { return ( <Container> <Routes> <Route path="/" element={<Home />} /> <Route path="/store" element={<Store />} /> <Route path="/about" element={<About />} /> </Routes> </Container> ); } export default App;
Create components Home, Store and About for the routes to work.
components/NavBar.tsx
import { Container, Nav, Navbar as NavBarBS } from "react-bootstrap"; import { NavLink } from "react-router-dom"; const NavBar = () => { return ( <NavBarBS className="bg-white shadow-sm mb-3"> <Container> <Nav> <Nav.Link to="/" as={NavLink}> Home </Nav.Link> <Nav.Link to="/store" as={NavLink}> Store </Nav.Link> <Nav.Link to="/about" as={NavLink}> About </Nav.Link> </Nav> </Container> </NavBarBS> ); }; export default NavBar;
- Store Page