I am rebuilding my personal site with React and have decided on the latest version of react-router-dom, I am building my App component to contain the navbar and then underneath the content I want to display, such as Home or Projects. This works fine on my /projects route but I cannot seem to work out how to render both App and Home on the index route. Is there a way? Here is what I have so far:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
// N.B. Routes replaces Switch as of V6
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
// Using <App/> here keeps the navbar but doesn't display the homepage content
<Route path="/" element={<App/>}>
// But using <Home/> loses the navbar
// Should I have my Navbar component in here somewhere or within the App?
<Route path="projects" element={<Projects/>}/>
</Route>
</Routes>
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
function App() {
// Help?
}
function Navbar() {
return (
<header> // Very crude example as I'm self-answering, in production I'll rename the component to Header
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/projects">Projects</Link>
</li>
</ul>
</nav>
</header>
}
function Home() {
return <h1>Home</h1>
}
function Projects() {
return <h1>Projects</h1>
}
If you followed the tutorial for React-Router 6 and used the createBrowserRouter function, and don't want to change to using <BrowserRouter>, you can do the following conversion:
const router = createBrowserRouter([
{
path: "/",
element: <Root/>
},
{
path: "/somePath",
element: <SomePath/>
}
])
root.render(
<div>
<NavBar/>
<RouterProvider router={router}/>
</div>
)
Navbar shows error useHref() may be used only in the context of a <Router> component
Restructure your createBrowserRouter object so that you have a path "/" with your Navbar component and an <Outlet/>.
import {Outlet} from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <NavbarWrapper/>
children:[
{
path: "/", // yes, again
element: <Root/>
},
{
path: "/somePath",
element: <SomePath/>
},
]
}
])
function NavbarWrapper(){
return (
<div>
<Navbar/>
<Outlet/>
</div>
)
};
The app can just unconditionally render the Navbar, and move the Routes component and routing to App. The index file renders App into the BrowserRouter.
App
function App() {
return (
<>
<Navbar />
<Routes>
<Route path="/" element={<Home/>}>
<Route path="projects" element={<Projects/>}/>
</Routes>
</>
);
}
index.js
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With