0

I have a little problem with my router in React. I have 2 components: Main and Compose.

When I go to mysite.com/ is render only Main (which is good), but when I go to mysite.com/compose only the Main is render, the Compose is not rendered. I want both to be rendered when you are on /compose.

How I can fix this?

return (
    <>
        <LeftSidebar />
        <div className="content">
            <Routes>
                <Route path="/" element={<Main />}>
                    <Route index element={<Main />} />
                    <Route path="compose" element={<Compose />} />
                </Route>
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="*" element={ <h1>Not found (404)</h1> } />
            </Routes>
        </div>
        <RightSidebar />
    </>
);
Galbert
  • 177
  • 1
  • 8

3 Answers3

0

Edit this

<Route path="compose" element={<Compose />} />

to

<Route path="/compose" element={<Compose />} />
kapildevsharma
  • 199
  • 1
  • 4
  • 17
0

I think this way will fix the bug

return (
    <>
        <LeftSidebar />
        <div className="content">
            <Routes>
                <Route path="/" element={<Main />}>
                <Route path="/compose" element={<Compose />} />
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="*" element={ <h1>Not found (404)</h1> } />
            </Routes>
        </div>
        <RightSidebar />
    </>
);
0

I just found how can I do that. I just need to import { Outlet } from 'react-router-dom'; and use <Outline /> on the bottom of my Main component which will allow to render the "sub-route" (if I am on the specified location path)

return (
    <>
        <LeftSidebar />
        <div className="content">
            <Routes>
                <Route path="/" element={<Main />}>
                    <Route path="compose" element={<Compose />} />
                </Route>
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="*" element={ <h1>Not found (404)</h1> } />
            </Routes>
        </div>
        <RightSidebar />
    </>
);
Galbert
  • 177
  • 1
  • 8