Home > Software design >  <Link> tag from React Router Dom V6 not working as expected
<Link> tag from React Router Dom V6 not working as expected

Time:04-20

I'm trying to create a header with links to their respective componenets. Using the a tag to redirect to a component works fine.

The Routes also work properly when the URL is changed manually by me. But when I use the Link tag to redirect it breaks the site and renders a blank page. Take a look at my code below...

App.js

<Router>
      <Routes>
        <Route path="/" exact element={<Hero />}></Route>
        <Route path="experience" element={<Experience />}></Route>
        <Route path="photos" element={<Photography />}></Route>
      </Routes>
</Router>

Header.js

 <nav>
   <ul>
      <li>
         <Link to="/">Home</Link> // using Link renders blank page
      </li>
      <li>
         <Link to="/experience">Experience</Link> // using Link renders blank page
     </li>
      <li>
        <a href="/photos">Photography</a> // works fine
      </li>
   </ul>
 </nav>

I don't even need to click the Link for the site to break, it automatically renders a blank page when the Link tag is used.

Please let me know where I'm going wrong

CodePudding user response:

So, basically the issue was that I'd used the Link tag outside the React Router Context. That was breaking the website.

App.js (Before)

function App() {
 return (
 <Layout>
  <div className="App">
    <Router>
      <Routes>
        <Route path="/" exact element={<Hero />}></Route>
        <Route path="experience" element={<Experience />}></Route>
        <Route path="photos" element={<Photography />}></Route>
        <Route
          path="*"
          element={
            <main style={{ padding: "1rem" }}>
              <p>There's nothing here!</p>
            </main>
          }
        />
      </Routes>
    </Router>
  </div>
</Layout>
);
}

App.js (After)

function App() {
 return (
 <div className="App">
  <Router>
    <Layout>
      <Routes>
        <Route path="/" exact element={<Hero />}></Route>
        <Route path="experience" element={<Experience />}></Route>
        <Route path="photos" element={<Photography />}></Route>
        <Route
          path="*"
          element={
            <main style={{ padding: "1rem" }}>
              <p>There's nothing here!</p>
            </main>
          }
        />
      </Routes>
    </Layout>
  </Router>
</div>
);
}

You can find some more deatils realted to this issue here

CodePudding user response:

The Header component is outside of the Router context, That seems to be the problem.

  • Related