I am trying to create a simple layout of header sidebar and mainscreen in react and have tried everything to bring the outlet in the mainscreen component but it always has block scope at the end of the page
The output I am getting with router component at bottom of page
CodePudding user response:
Issue
The Layout
component is rendering the sidebar and "Mainscreen" div element and the Routes
and Routes
are rendered below it.
export default function App() {
return (
<div className="App">
<BrowserRouter>
<Layout /> // <-- layout here
<Routes> // <-- routes under it
<Route path="home" element={<Home />}>
<Route path="dashboard" element={<Dashboard />} />
<Route path="sales" element={<Sales />} />
<Route path="inventory" element={<Inventory />} />
</Route>
</Routes>
</BrowserRouter>
</div>
);
}
Solution
The Layout
component needs to render an Outlet
and be rendered as a layout route.
import React from "react";
import { Sidebarz } from "./Components/Sidebar";
import { Outlet } from "react-router-dom";
export const Layout = () => {
return (
<div>
<div
className="container"
style={{
display: "grid",
gridAutoFlow: "row dense",
gridTemplateColumns: "0.7fr 1.3fr 1fr",
gridTemplateRows: "0.3fr 1.7fr 1fr",
gap: "0px 0px",
gridTemplateAreas:
'"header header header"\n "sidebar Mainscreen Mainscreen"\n "sidebar Mainscreen Mainscreen"\n'
}}
>
<div
className="header"
style={{ gridArea: "header", textAlign: "center" }}
>
<h1>Header here</h1>
</div>
<div className="sidebar" style={{ gridArea: "sidebar" }}>
<Sidebarz />
</div>
<div
className="Mainscreen"
style={{
gridArea: "Mainscreen",
textAlign: "center",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<Outlet /> // <-- Outlet for nested routes
</div>
</div>
</div>
);
};
export default function App() {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route element={<Layout />}> // <-- layout route
<Route path="home" element={<Home />}>
<Route path="dashboard" element={<Dashboard />} />
<Route path="sales" element={<Sales />} />
<Route path="inventory" element={<Inventory />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
</div>
);
}