I have a ReactJS application with basic routing like this
import React from 'react'
import { Routes, Route } from "react-router-dom"
import Global from './global'
import Authentication from './authentication'
const App = () => {
return (
<Routes>
<Route path="/" element={<Global />} />
<Route path="/login" element={<Authentication />} />
</Routes>
)
}
export default App
Inside the Global component I have this code
import React from "react";
import Header from "./Header";
import Sidebar from "./Sidebar";
import MainContent from "./MainContent";
const Global = () => {
return (
<>
<Sidebar />
<Header />
<MainContent />
</>
);
};
export default Global;
I want to embed some routing inside the MainContent component like this
import React from 'react'
import { Routes, Route } from "react-router-dom"
import Sales from '../../pages/Sales'
import Products from '../../pages/Products'
const MainContent = () => {
return (
<div className='content-body'>
<Routes>
<Route path="/sales" element={<Sales />} />
<Route path="/products" element={<Products />} />
</Routes>
</div>
)
}
export default MainContent
I am using react-router-dom@6
but this routing is not working properly. The embedded route may be causing the issues.
2
Answers
You’ll need to embed in another way and if you want to add your
Sidebar
andHeader
, you’ll need to add aLayout
with anOutlet
Check for more here : https://reactrouter.com/en/main/components/outlet
Here’s what you can do :
in you
App
In your
Layout
I think it should be good.
The routes/routed components are not configured correctly to allow for rendering descendent or nested routes.
Descendent Routes
In order for the
MainContent
component, viaGlobal
rendered on the"/"
path, to render descendent routes its parent route necessarily needs to append the path wildcard matcher"*"
to its path so descendent routes can also be matched.path="/*"
instead of justpath="/"
.Nested Routes
You could also convert
MainContent
into a layout route where it renders anOutlet
component for nested routes to render their content into.MainContent
See layout routes and outlets for more details.