I just started to build this shopping cart project. and I am able to display the components fine when I manually change the url but -- When I add the Link element to the Nav my app stops working. Why is that happening?
I want to the display the different components when they are clicked.
When I add the Link Element to the navigation bar I get the following errors in the console:
The above error occurred in the <Link> component
Uncaught Error: useHref() may be used only in the context of a <Router> component.
import React from "react";
import { Link } from 'react-router-dom'
function Nav () {
return (
<nav>
<h3>Logo</h3>
<ul>
<Link to="/home">
<li>Home</li>
</Link>
<Link to="/shop">
<li>Shop</li>
</Link>
<Link to="/cart">
<li>Cart</li>
</Link>
</ul>
</nav>
)
}
export default Nav;
import React from 'react';
import {BrowserRouter, Route, Routes} from 'react-router-dom';
import Home from './components/main/Home'
import Cart from './components/main/Cart'
import Shop from './components/main/Shop'
import About from './components/main/About'
function RouteSwitch() {
return (
<BrowserRouter>
<Routes>
<Route path='/' exact element={<Home />} />
<Route path='/shop' element={<Shop />} />
<Route path='/about' element={<About />} />
<Route path='/cart' element={<Cart />} />
</Routes>
</BrowserRouter>
);
}
export default RouteSwitch;
import './App.css';
import React from 'react';
import RouteSwitch from './RouteSwitch';
import Nav from './components/Nav'
import Footer from './components/Footer';
function App() {
return (
<div>
<Nav/>
<RouteSwitch />
<Footer/>
</div>
);
}
export default App;
CodePudding user response:
Your nav
component must be inside of Router
component.
<BrowserRouter>
<Nav /> // here
<Routes>
<Route path='/' exact element={<Home />} />
<Route path='/shop' element={<Shop />} />
<Route path='/about' element={<About />} />
<Route path='/cart' element={<Cart />} />
</Routes>
<Footer />
</BrowserRouter>