Home > Back-end >  Reactjs react-router-dom
Reactjs react-router-dom

Time:12-06

Cannot realize how it works, Have two routes, but in two cases opening only the one route with path '/'.

<HashRouter>
<Routes>
<Route path='/' element={<HomeScreen />}></Route>
<Route path='/about' element={<AboutScreen />}></Route>
<Routes/>
<HashRouter/>

React router dom version 6.0.2

CodePudding user response:

<Route exact path='/'>
     <HomeScreen />}
</Route>
<Route exact path='/about'>
      <AboutScreen />
</Route>

try writing them like this?

CodePudding user response:

I don't know if you have wrapped the routes, but routes has to be wrapped inside <Routes></Routes> if u are using react-router-dom v6 otherwise you have to use a <Switch></Switch> if u are using <= v5. This helps in just picking up one of the routes while checking for route requested.

<Routes>
   <Route path='/about' element={<AboutScreen />}></Route>
   <Route path='/' element={<HomeScreen />}></Route>
</Routes>

Note: Check them once and comment if any query. Since, I haven;t seen ur code, then, I can suspect this issue

Also check if order of route inclusion also effects the result

CodePudding user response:

React routes work by priority from top to bottom; any rule that matches will be evaluated.. and the / matches both / and /about.

So to be able to solve your problem, you either have to put the / route at the end of all routes or you can add an exact keyword on the / route to tell the router that this has to match exactly for it to work..

<Route path='/' exact element={<HomeScreen />}></Route>
<Route path='/about' element={<AboutScreen />}></Route>

or

<Route path='/about' element={<AboutScreen />}></Route>
<Route path='/' element={<HomeScreen />}></Route>

I usually prefer the first approach.

CodePudding user response:

Here for you minimal example of routing with react-router v6.

import { render } from "react-dom";
import { BrowserRouter, Routes, Route } from "react-router-dom";


const Home = () => <div>Hello HomePage </div>;

const AboutPage = () => <div>Hello AboutPage </div>;

render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<AboutPage />} />
    </Routes>
  </BrowserRouter>,
  document.getElementById("root")
);

Check out working demo

CodePudding user response:

Try this :


import React from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import HomeScreen from "Path of HomeScreen";
import AboutScreen from "Path of AboutScreen";

export default function Routes() {
  return (
    <BrowserRouter>
      <Switch>
          <Route path='/' exact component={HomeScreen}></Route>
          <Route path='/about' component={AboutScreen}></Route>
      </Switch>
    </BrowserRouter>
  );
}

  • Related