skip to Main Content

Why my outlet is not working in react-router-dom. All my components worked fine until I use Outlet and after using outlet my navigation component is not showing while other component seems to render.

import Home from "./Routes/Home/Home.component";
import { Routes, Route, Outlet } from "react-router-dom";

const Navigation = () => {
  return (
    <div>
      <div>
        <h1>Hello I am Navigation!!!</h1>
      </div>
      <Outlet />
    </div>
  );
};

const Shop = () => {
  return <h2>I am shop component</h2>
}

const App = () => {
  return (
    <Routes>
      <Route path='/' element={<Navigation />} />
      <Route index element={<Home />} />
      <Route path='shop' element={<Shop />} />
    </Routes>
  );
};

export default App;

I am receiving this:
enter image description here

and I want navigation component to render all above and persist every time I navigate to elsewhere.

2

Answers


  1. for using of Outlet you need Add children to Route Component

    const App = () => {
      return (
        <Routes>
            <Route path='/' element={<Navigation/>}>
              <Route path="url1" element{<ChildElemnt1 />} />
              <Route path="url2" element{<ChildElemnt2 />} />
              <Route path="url3" element{<ChildElemnt3 />} />
              ...
            </Route>
            <Route index element={<Home />} />
            <Route path='shop' element={<Shop/>}/>
        </Routes>
      );
    };
    
    Login or Signup to reply.
  2. The Navigation component isn’t rendered as a layout route with nested routes, so nothing is rendered into the Outlet it is rendering. Navigation will also only render on path "/".

    If you want the Navigation component to render always then you can render it alone outside the routes.

    const Navigation = () => {
      return (
        <div>
          <div>
            <h1>Hello I am Navigation!!!</h1>
          </div>
        </div>
      );
    };
    
    const App = () => {
      return (
        <>
          <Navigation />
          <Routes>
            <Route path='/'>
              <Route index element={<Home />} />
              <Route path='shop' element={<Shop />} />
            </Route>
          </Routes>
        </>
      );
    };
    

    Or you can utilize it as a layout route such that it wraps nested routes that render their element into the Outlet.

    const Navigation = () => {
      return (
        <div>
          <div>
            <h1>Hello I am Navigation!!!</h1>
          </div>
          <Outlet />
        </div>
      );
    };
    
    const App = () => {
      return (
        <Routes>
          <Route path='/' element={<Navigation />} />
            <Route index element={<Home />} />
            <Route path='shop' element={<Shop />} />
          </Route>
        </Routes>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search