'How can I configure React router correctly to navigate to a new page?

I have a navbar containing 3 Anchors, I want to navigate between different pages when clicking on each one. I've used react-router (version 6.3.0) to achieve this but I faced two issues and I got a stack.

The first one is when I click on a LaunchApp anchor, the URL change to http://localhost:3000/launchApp the page shows its content but on the top of the home page, not on a new page. The second one is when I refresh the page, the page doesn't go back to the home page (http://localhost:3000) but it renders the last anchor I clicked on.

App.js

return (
  <s.Main>
    <>  
      <Navbar/>
      <HeroSection/>
      <About/>
      <Testimonials/>
      <ContactForm/>
      <Footer/>
      <Routes>
        <Route path="/" element={<HeroSection/>}/>
        <Route path="/about" element={<About/>}/>
        <Route path="/launchApp" element={<LaunchApp />}>
        <Route path="submitSubscription" 
                element={<SubmitSubscription/>}/>
        <Route path="CancelSubscription" 
                element={<CancelSubscription />}/>
        </Route>
      </Routes> 
    </>
  </s.Main>
);

Navbar return

return (
  <nav> 
    <ul>
      <li>
        <Link to="/">Home</Link> 
      </li>
      <li>
        <Link to="/about">About</Link> 
      </li>
      <li>
        <Link to="/launchApp">Launch App</Link>     
      </li>      
    </ul>
  </nav>
)

Am I missing something?



Solution 1:[1]

You are rendering several components twice, once unconditionally in the App, and then again conditionally in a route. If I'm understanding correctly, you don't want the routed content to duplicate the main page content.

Remove the duplicate components not on a route and move the routes up between the Navbar and Footer components.

Example:

return (
  <s.Main>
    <Navbar/>
    <Routes>
      <Route path="/" element={<HeroSection />} />
      <Route path="/about" element={<About />} />
      <Route path="/launchApp" element={<LaunchApp />} />
    </Routes>
    <Testimonials/>
    <ContactForm/>
    <Footer/>
  </s.Main>
);

To handle redirecting back to the "main" page on a page load, use the useNavigation hooks to redirect in a mounting useEffect hook in the app component.

Example:

import { Routes, Route, useNavigate } from 'react-router-dom';

const App = () => {
  const navigate = useNavigate();

  React.useEffect(() => {
    navigate("/", { replace: true });
  }, []); // note *

  return (
    <s.Main> ... </s.Main>
  );
};

* The linter may complain about missing dependency navigate, it's a stable reference and is safe to add.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese