devYuraKim / react

udemy - jonas schmedtmann
0 stars 0 forks source link

Re11-worldwise > src> App, pages > Homepage | <PageNav> error #16

Closed devYuraKim closed 2 months ago

devYuraKim commented 2 months ago

In App component, the PageNav component didn’t render and threw an error.

App component

function App() { 
  return (
    <>
      <PageNav />
      <p>constant element</p>

      <BrowserRouter>
        <Routes>
          <Route index element={<Homepage />} />
          <Route path="/product" element={<Product />} />
          <Route path="/pricing" element={<Pricing />} />
          <Route path="*" element={<PageNotFound />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

The above error occurred in the component:

NavLinkWithRef@http://localhost:5173/node_modules/.vite/deps/react-router-dom.js:5353:12 Logo nav PageNav App

Funny thing is, the same PageNav component worked fine inside the Homepage component, even though both are using similar structures.

Homepage component

export default function Homepage() {
  return (
    <main className={styles.homepage}>
      <PageNav />
      <section>
        <h1>
          You travel the world.
          <br />
          WorldWise keeps track of your adventures.
        </h1>
      </section>
    </main>
  );
}
devYuraKim commented 2 months ago

TL;DR: BrowserRouter provides routing context

Moving the PageNav component inside the BrowserRouter component resolved the error.

function App() {
  return (
    <>
      <p>constant element</p>

      <BrowserRouter>
        <PageNav />

        <Routes>
          <Route index element={<Homepage />} />
          <Route path="/product" element={<Product />} />
          <Route path="/pricing" element={<Pricing />} />
          <Route path="*" element={<PageNotFound />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

PageNav contains NavLink component, which depends on the BrowserRouter to provide routing context. Without being inside BrowserRouter, it doesn't have access to important routing data like the current path or navigation functions, leading to errors.