I got a problem with the lib ‘react-router-dom’. This is my first time using React with Typescript;
Everything is working fine until I put the from the ‘react-router-dom’ when all the page goes down;
Basically I want to put three items on header (Home, About and login) and change the page when I click on them. The errors comes when I put the tag on the component, if I just update the App.jsx and change the page writing on URL, it works fine.
App.jsx
import 'bootstrap/dist/css/bootstrap.min.css';
// --- component ---
import MainHeader from './components/MainHeader';
import MainFooter from './components/MainFooter';
// --- pages ---
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
// --- style ---
import './App.css';
function App() {
return (
<div className="App">
<div className='sec-header'>
<MainHeader />
</div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />}></Route>
<Route path="/about" element={<About />}></Route>
<Route path="/contact" element={<Contact />}></Route>
</Routes>
</BrowserRouter>
<div className='sec-footer'>
<MainFooter />
</div>
</div>
);
}
export default App;
MainHeader
import './MainHeader.css'
import { Link } from 'react-router-dom'
function MainHeader() {
return (
<div className="p-3">
<nav className="navbar navbar-expand">
<ul className="rounded-4 d-flex m-auto p-0">
<li className="btn btn-header fs-5 p-0 py-2 px-4 mx-3 border-bottom rounded-0 w-100">
<Link to="/">Home</Link>
</li>
<li className="btn btn-header fs-5 p-0 py-2 px-4 mx-3 border-bottom rounded-0 w-100">
<Link to="/about">About</Link>
</li>
<li className="btn btn-header fs-5 p-0 py-2 px-4 mx-3 border-bottom rounded-0 w-100">
<Link to="/login">Login</Link>
</li>
</ul>
</nav>
</div>
)
}
export default MainHeader
2 Errors on Console
1. Uncaught Error: useHref() may be used only in the context of a <Router> component.
2. react-dom.development.js:18687 The above error occurred in the <Link> component:
Do you know what it coulkd be?
2
Answers
It’s probably because your MainHeader component is outside of the BrowserRouter component in the app.jsx file. If you want your header to be seen on all your pages, put it inside your BrowserRouter component, but outside your Routes component:
}
Move Mainheader component inside BrowserRouter as below to fix this issue