I got stuck to the following situation in React 18
. I have defined two components as in: AppLayout
and AddEvent
.
My App.tsx
file looks like this:
import React from "react";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import AppLayout from "../views/layout/AppLayout";
import './App.css';
import AddEvent from "../views/event/AddEvent";
const App: React.FC = () => {
return (
<Router>
<Routes>
<Route path="/" element={<AppLayout />}/>
<Route path="/events/add" element={<AddEvent />}/>
</Routes>
</Router>
)
}
export default App;
In AppLayout.tsx
, I have a button that allows me to navigate to AddEvent
component:
<Space wrap>
<Button type="primary" onClick={() => navigate('/events/add')}>Add new event</Button>
</Space>
When I run the app and land to the homepage, I’m able to navigate to my second page via the button. Tho, when refresing the AddEvent
page, I get an empty page and the following error:
GET http://localhost:8080/events/main.js net::ERR_ABORTED 404 (Not
Found)
and
Refused to execute script from ‘http://localhost:8080/events/main.js’
because its MIME type (‘text/html’) is not executable, and strict MIME
type checking is enabled.
However, if I change the link to the AddEvent
page from "/events/add" to "/events-add" I am not getting this error anymore and I can even refresh the page. Although I solved the issue, could anyone explain why is this happening? Many thanks.
2
Answers
What build tool are you using? create-react-app or Vite?
The issue is related to the development server. you should configure the development server to always serve the
index.html
file, regardless of the requested URL. This way, React Router can handle the routing on the client side.In React Router, a URL or path pattern is divided into segments. Each segment is the part of the path between the ‘/‘ characters. For example, in the path /events/add, there are two segments: "events" and "add".
When working with nested routes, it’s important to structure them properly to avoid conflicts and confusion. In the original code you provided,
tries to define a nested route directly. However, this can lead to issues because the router may interpret "add" as a separate segment rather than a nested route.
To resolve this issue, you can modify the code to use nested routes correctly:
In this updated code, we define a parent route for "/events" using the component. Inside the parent route, we define a nested route for "/add". This structure makes it clear that "/add" is a nested route under "/events" and avoids any confusion in the routing process.
If you want to learn more about nested routing and segments in React Router, you can refer to the documentation at https://reactrouter.com/en/main/start/concepts#segment.