Issue
I use Vite to create a React app.
Routes.tsx
import { RouteObject, createBrowserRouter } from "react-router-dom";
import App from "../layout/App";
import HomePage from "../../feautures/home/HomePage";
import CreateRegistration from "../../feautures/createRegistration/createRegistration";
export const routes: RouteObject[] = [
{
path: '/',
element: <App />,
children: [
{ path: '', element: <HomePage /> },
{ path: 'createRegistrationForm', element: <CreateRegistration /> }
]
}
];
export const router = createBrowserRouter(routes);
In my vite.config.ts I have
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
// https://vitejs.dev/config/
export default defineConfig({
//base: '/registration/',
server:{
port: 3000
},
plugins: [react()],
})
and everything works great at "http://127.0.0.1:3000/"
but the moment in my vite.config.ts
when I uncomment base: '/registration/',
and go to "http://127.0.0.1:3000/registration/"
I get all 404 errors for all routes. I'm not sure what I am missing to run a React app using Vite in a subfolder.
Solution
The piece that I believe is missing is setting a basename
value for the BrowserRouter
to match where it's routing/navigating relative to.
The basename of the app for situations where you can't deploy to the root of the domain, but a sub directory.
The basename
passed to the router should match the Vite configuration.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
// https://vitejs.dev/config/
export default defineConfig({
base: '/registration/',
server:{
port: 3000
},
plugins: [react()],
});
export const routes: RouteObject[] = [
{
path: '/',
element: <App />,
children: [
{ index: true, element: <HomePage /> },
{ path: 'createRegistrationForm', element: <CreateRegistration /> }
]
}
];
export const router = createBrowserRouter(routes, {
basename: "/registration/",
});
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.