reactjsreact-router-domreact-componentmulti-page-application

React Router is not working and returns a blank page


I am trying to develop a multi-page React App and I tried to use React Router but when I hit Save and reload the page I get a blank page. This is what I have: The Home component:

import React from "react";
import Navbar from './components/Navbar';
import Hero from './components/Hero';
import AboutUs from './components/AboutUs';
import Footer from './components/Footer';

export default function Home() {
    return (
      <div>
        <Navbar />
        <Hero />
        <AboutUs />
        <Footer />
      </div>
    )
}

This is App component:

import React from 'react';
import Home from './Home';
import { Route, Router, browserHistory, Link } from "react-router-dom";

export default function App() {
  return (
        <Router history={browserHistory}>
            <Router exact path="/" component={Home} />
        </Router>
  );
}

And finally this is the index.js file:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <BrowserRouter>
      <App />
    </BrowserRouter>
);

When I hit Save and reload the page, because I am doing this on replit.com, all I get is a blank page. What am I doing wrong?

I tried to import Router from react-router-dom and wrap my <Route /> tags within a <Router /> tag and still get the same.


Solution

  • Here is a working version of your App component

    import { Route, Routes } from "react-router-dom";
    import Home from "./home";
    import "./styles.css";
    
    export default function App() {
      return (
        <Routes >
            <Route exact path="/" element={<Home/>} />
        </Routes>
    );
    }
    

    Use Routes instead of Router and use element prop in Route to specify what will be rendered.

    As for history, you can use useNavigate hook:

      const nav = useNavigate();
      const handleCheckout = () => nav("/");