Home > Net >  react routing always showing the content of "/" route
react routing always showing the content of "/" route

Time:04-01

I've just started continuing my react app today but suddenly the routing is not working. whatever url I put in, it always shows the component inside path="/", which is the Hello World in Test1.js. I'm using react-router-dom version 6.2.2

this is my code:

App.js

import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Test1 from "./components/Test1";
import Test2 from "./components/Test2";

const App = () => {

  return (
    <Router>
      <Header />

      <div className="container hero is-fullheight">
        <Routes>
          <Route path="/" element={<Test1 />} />
          <Route path="/asd" element={<Test2 />} />
        </Routes>
      </div>
    </Router>
  );
};

export default App;

Test1.js

const Test1 = () => {
  return <div><h1>Hello World</h1></div>;
};

export default Test1;

Test2.js

const Test2 = () => {
  return (
    <div><h2>Lorem ipsum dolor sit amet.</h2></div>
  )
}

export default Test2

any help is appreciated..

CodePudding user response:

Try to use BrowserRouter instead HashRouter

CodePudding user response:

Try this

...
  <div className="container hero is-fullheight">
    <Routes>
      <Route path="/" element={<Test1 />} />
      <Route path="asd" element={<Test2 />} />  --> // Here the path without slash
    </Routes>
  </div>
...

At /asd it will render the Test2 component.

Doc here.

  • Related