Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router switch not working as expected

I'm learning react and got stuck at react-routes

consider the following:

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

import HelloWorld from "./HelloWorld.jsx";

const Root = () => {
  return (
    <BrowserRouter>
      <div>
        <Switch>
          <Route path="/" exact component={HelloWorld} />
          <Route component={NoMatch} />
        </Switch>
      </div>
    </BrowserRouter>
  );
};

function NoMatch({ location }) {
  return (
    <div>
      <h3>
        No match found
      </h3>
    </div>
  );
}

export default Root;

on '/' this route, it renders HelloWorld component as expected but on other routes for examples abc it displays Cannot GET /abc instead of No match found

like image 299
Bhavay Anand Avatar asked Sep 06 '25 03:09

Bhavay Anand


1 Answers

First you check your react version then after do like this if v5.1 and above

In order to use v6, you'll need to convert all your elements to <Routes>

You want to replace component to element into <Route ...>

example:- App.js

import Home from "./Home";
import About from "./About";

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

function App() {
  return (
    <Router>
      <Routes>
        <Route exact path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}


export default App;

after that your switch related error maybe gone! if still not working comment me i will help you

like image 128
Surekha kambariya Avatar answered Sep 07 '25 21:09

Surekha kambariya