Search code examples
javascriptreactjsreact-router-dom

React Router Dom v5 not redirecting in my website


I have a main website that is accessible to everyone. And I have another page that can only be seen once you press a button that would redirect you to said page. I have already implemented my routes on my App.js and placed the , however when I click the button, it does not redirect me to the specified page.

App.js:

import React, { useState, useEffect } from 'react';
import './App.css';
import Navbar from './Components/Navbar';
import Footer from './Components/Footer';
import Dropdown from './Components/Dropdown';
import Hero from './Components/Hero';
import AboutUs from './Components/AboutUs';
import OurProgram from './Components/OurProgram';
import Research from './Components/Research';
import Data from './Components/Data';
import Loan from './Components/Loan';
import ScrollToTop from './Components/ScrollToTop';
import Gov from './Components/Gov';


import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { Button } from 'react-bootstrap';

{/* Backend of Toggle function */ }
function App() {
  const [isOpen, setIsopen] = useState(false)

  const toggle = () => {
    setIsopen(!isOpen)
  }

  return (
    <>
      <Navbar toggle={toggle} />
      <Dropdown isOpen={isOpen} toggle={toggle} />
      <Switch>
        <Route path="/">
          <Hero />
          <AboutUs />
          <OurProgram />
          <Research />
          <Loan />
          <Footer />
        </Route>

        <Route path="/Gov">
          <Gov />
        </Route>

      </Switch>



    </>
  );
}

export default App;

link used:

<Link to="/Gov" className='bg-yellow-500 text-white font-bold p-5 mb-3  rounded-lg md:p-18 text-2xl '>Useful gov links</Link>

How can I solve this issue?


Solution

  • It is because of your Switch, as it is defined, you will always be at the home page cause this / and this /jfdf both will match the first path. A solution could be changing the order like so:

     <Switch>
        <Route path="/Gov">
          <Gov />
        </Route>
        <Route path="/">
          <Hero />
          <AboutUs />
          <OurProgram />
          <Research />
          <Loan />
          <Footer />
        </Route>      
     </Switch>
    

    Or use the exact property, like so:

    <Switch>
      <Route exact path="/">
        <Hero />
        <AboutUs />
        <OurProgram />
        <Research />
        <Loan />
        <Footer />
      </Route>
      <Route  path="/Gov">
        <Gov />
      </Route>
    </Switch>