skip to Main Content

I’ve been trying to connect components to links, but whenever i write more than one route in <Routes>
react seems to ignore it, and does not respond to anything. Also used <StrictMode> to see what happens inside program
Here is my code:

import {Routes,Route } from "react-router-dom";
import Home from './pages/Home';
import Teacher from "./pages/TeacherComponent";
import Navbar  from "./pages/Navbar";
import { StrictMode } from 'react';

const App = () => {
  return (
    <StrictMode>
    <div className="mx-12 my-4 rounded px-8 py-4 bg-fuchsia-100 h-full">
      <Navbar/>
      <Routes>
        <Route path="*"  element={<Home />} />
        <Route path="teacher" element={<Teacher />}/>
      </Routes>
    </div>
    </StrictMode>

  );
};

Screenshot from plugin analysing script

I’ve tried changing react-router-dom version, to use <Switch>, but it doesn’t work too

3

Answers


  1. Routes are normally processed in the order in which you define them. Here, you are having a catch-all route as the first entry <Route path=* . So, all routes will get matched to this, and always Home component will be displayed.

    To fix this, switch the order of the route entries so that the most specific entries comes at the top

     <Routes>
      <Route path="teacher" element={<Teacher />}/>
      <Route path="*"  element={<Home />} />
    </Routes>
    Login or Signup to reply.
  2. The path prop in the second Route component should be "/teacher" instead of just "teacher".

    So just replace it and run again and I am sure it will work.

    Do let me know how it goes. Thanks.

    Login or Signup to reply.
  3. I think if you add exact to each route, React won’t ignore the path specified again.
    thanks…..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search