skip to Main Content

Every time a dotnet react application is created dotnet places Routes for further React development. My goal is to do something similar using node (as webserver) and Express, webpack and React. Yet, I got to a problem that I can not escape from. My node application has in its package.json:

  "dependencies": {
    "express": "^4.18.3",
    "pg": "^8.11.3",
    "sequelize": "^6.37.1"
  }

My React App package.json has:

   "dependencies": {
        "localforage": "^1.10.0",
        "match-sorter": "^6.3.4",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-router-dom": "^6.22.3",
        "sort-by": "^1.2.0"
      },

My "router" App.js is:

import {BrowserRouter, Routes, Route, Switch} from "react-router-dom" 
import Home from "../home/Home" 
import About from "../about/About" 

// based on https://www.knowledgehut.com/blog/web-development/routing-in-reactjs

function App(){ 
   return ( 
      
         <BrowserRouter> 
            <Routes> 
               <Route path="/"      element={<Home/> }></Route> 
               <Route path="/about" element={<About/>}></Route>
            </Routes> 
         </BrowserRouter>   
)} 
export default App 

and my index.js is:

import React from 'react'
import { createRoot } from 'react-dom/client';

import App from "./App";

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

I am using node.js as web server and the node’s application index.js has:

app.get('*', (req, res) => {

  res.sendFile(__dirname + '/views/index.html');

  }

I am also using webpack that compiles and creates the respective index.js:

  {
    entry: path.resolve(__dirname, "./components/rootApp/index.js"),
    output: { 
              filename: "index.js",
              path: path.resolve(__dirname, "../public/") 
            },
    module: {
    rules: [
              {
                test: /.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                        loader: "babel-loader",
                        options:{
                            presets: ["@babel/preset-env", "@babel/preset-react"],
                        }
                    },
              },
            ],
        },
    mode:current_mode
  },

that will be uploaded by my index.html. The problem I got is that while I can run my website using http://localhost:3000/, if I use http://localhost:3000/about it goes to the server instead of being filtrated by React Router. I tried:

https://stackoverflow.com/questions/53141470/react-router-router-not-workingg

and similar links but nothing helps. Any suggestions?

2

Answers


  1. The problem I got is that while I can run my website using
    http://localhost:3000/, if I use http://localhost:3000/about it goes
    to the server instead of being filtrated by React Router.

    You are using a browser router so it’s acting as a SPA (single page application).

    So my guess is that the server needs to serve all paths to / or else yes, /about will be served by your server at said path on reload vs serving your index.html which contains your app/routing capabilities. You’re getting a 404 status code presumably on loading /about

    Everything looks good (assuming your package.lock file isn’t out of date with your package.json), so make sure whatever you are using to serve your app is routing all paths to / (index.html.)

    For example, with express as your server, you’d write something like:

    app.get('*', (req, res) => res.sendFile(path.resolve('path/to/my/index.html')));
    

    With nginx something like try_files where a 404 will send you to the index.html page.

    server {
        root /path/to/root;
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    

    https://superuser.com/questions/1199616/get-nginx-to-always-serve-index

    Think about it like this: when you load index.html directly and navigate TO /about using react-router-dom routing, it will do so correctly while preventing a "real" page load. Refreshing or directly navigating to /about will cause a real page load and load a non existing page (404 — no react router).

    Login or Signup to reply.
  2. maybe your problem is caused by depracated way you try to handle this situation.
    Recommend to see in react-router-dom documentation

    https://reactrouter.com/en/main/start/tutorial

    Your usecase:

     // index.js 
    
    
    const router = createBrowserRouter([
       {
         path: "/",
         element: <Home />,
       },
       {
         path: "/about",
         element: <About />,
       },
    ]);
    
    ReactDOM.createRoot(document.getElementById("root")).render(
      <React.StrictMode>
        <RouterProvider router={router} />
      </React.StrictMode>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search