The following code has some sort of error in the router App.js
import Home from './pages/Home.js'
import Invites from './pages/Invites.js'
import {createBrowserRouter,
createRoutesFromElements,
Route,
Link,
RouterProvider,
MemoryRouter} from 'react-router-dom'
import './App.css';
const Root = () =>{
return(
<>
<h1>Is it working?</h1>
</>
)
}
function App() {
const router = createBrowserRouter(createRoutesFromElements(
<Route path="/" element={<Root />} >
<Route index element={<Home />} />
<Route path="/invt" element={<Invites />} />
</Route>
)
)
return (
<>
<RouterProvider router={router}/>
<div className="App">
<MemoryRouter>
<Link to="invt">Invitations</Link>
</MemoryRouter>
</div>
</>
);
}
export default App;
The <Root>
and the content of the tag <div className="App">
renders, but the <Home>
doesn't.
When I click on the 'Invitations' link, nothing happens.
When I manually navigate to "localhost:3000/invt" the <Invites>
doesn't renders either.
Home
and Invites
are minimal pages made solely to test the router by now.
I expected the <Root>
to be rendered all the time, the <Home>
to be rendered at "localhost:3000" and the <Invites>
to be rendered at "localhost:3000/invt".
Also expected to enter the "localhost:3000/invt" when I clicked the text between <Link to="invt">
.
None of this happened.
PS: I am using react-router-dom 6.10 Must be important, since every tutorial I try to follow is very distinct from previous ones and leads to some new weird error.
The Root
component necessarily should render an Outlet
component for the nested routes to render their element
content into.
The link should also be rendered within the same router/routing context it is linking to.
Example:
import {
createBrowserRouter,
createRoutesFromElements,
Route,
Link,
RouterProvider,
Outlet
} from 'react-router-dom'
import Home from './pages/Home.js'
import Invites from './pages/Invites.js'
import './App.css';
const Root = () => {
return (
<>
<h1>Is it working?</h1>
<Outlet />
<div className="App">
<Link to="invt">Invitations</Link>
</div>
</>
)
}
function App() {
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Root />} >
<Route index element={<Home />} />
<Route path="/invt" element={<Invites />} />
</Route>
)
);
return <RouterProvider router={router} />;
}
export default App;