I am using createBrowserRouter
to manage routes, but unable to render any data from my components, why? I am navigating to the correct URL path it seems, but nothing displays from the components. In this example, no content from the about page.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
import React from 'react';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Skills from './Skills'
const router = createBrowserRouter([
{
path:'/',
element: <Home />,
children: [
{
path: 'about',
element: <About />
},
{
path: 'skills',
element: <Skills />
}
],
},
]);
function App() {
return (
<RouterProvider router={router} />
);
}
export default App;
The Home
component is rendered as a layout route, so it must render an Outlet
for the nested routes to render out their element
content.
Example:
import { Outlet } from 'react-router-dom';
const Home = () => (
<>
<Navbar />
...
<Outlet /> // <-- nested routes render content here
</>
);
const router = createBrowserRouter([
{
path:'/',
element: <Home />,
children: [
{ path: 'about', element: <About /> },
{ path: 'skills', element: <Skills /> }
],
},
]);
If you would like to render Home
, About
, and Skills
each on their own pages, independent from each other and the Navbar
then create a navbar layout route component that is separate from the Home
component UI.
Example:
import { Outlet } from 'react-router-dom';
const AppLayout = () => (
<>
<NavBar />
<Outlet />
</>
);
const Home = () => (
<>
...
</>
);
const router = createBrowserRouter([
{
path:'/',
element: <AppLayout />,
children: [
{ index: true, element: <Home /> },
{ path: 'about', element: <About /> },
{ path: 'skills', element: <Skills /> }
],
},
]);
For more details see: