I want to add the base URL to my react.js project. However I had tried couple of methods that did not work.
For example, if my project url is :
JavaScript
x
2
1
http://www.myproject.com/
2
It should appear in address bar as :
JavaScript
1
4
1
http://www.myproject.com/app
2
http://www.myproject.com/app/home // If home page
3
http://www.myproject.com/app/about // If about page
4
Below is my project code.
index.js
JavaScript
1
23
23
1
import "./index.css"
2
import React from 'react';
3
import ReactDOM from 'react-dom/client';
4
import { AuthProvider } from './context/AuthProvider';
5
import {BrowserRouter, Routes, Route} from 'react-router-dom'
6
import { disableReactDevTools } from '@fvilers/disable-react-devtools';
7
import App from './App';
8
9
if (process.env.NODE_ENV === 'production') {
10
disableReactDevTools();
11
}
12
13
const root = ReactDOM.createRoot(document.getElementById('root'));
14
root.render(
15
<BrowserRouter>
16
<AuthProvider>
17
<Routes>
18
<Route path="/*" element={<App />} />
19
</Routes>
20
</AuthProvider>
21
</BrowserRouter>
22
);
23
App.js
JavaScript
1
41
41
1
import Layout from './components/authController/Layout'
2
import Login from './components/authController/Login';
3
import Home from './components/authController/Home'
4
import AllUser from './components/authController/AllUser'
5
import RequireAuth from './components/authController/RequireAuth';
6
import PersistLogin from './components/authController/PersistLogin';
7
import Logout from './components/authController/Logout';
8
import Missing from './Missing';
9
import {Routes, Route, Navigate} from 'react-router-dom'
10
11
12
function App() {
13
return (
14
<div>
15
<Navbar/>
16
<Routes>
17
<Route path="/" element={<Layout />}>
18
{/* public routes */}
19
<Route path="login" element={<Login />} />
20
<Route path="loggedOut" element={<Logout />} />
21
22
{/* we want to protect these routes */}
23
<Route element={<PersistLogin />}>
24
<Route path="/" element={<Navigate to="/home" replace />} />
25
<Route path="home" element={<Home/>} />
26
27
<Route element={<RequireAuth/>}>
28
<Route path="alluser" element={<AllUser />} />
29
</Route>
30
31
</Route>
32
{/* catch all */}
33
<Route path="*" element={<Missing />} />
34
</Route>
35
</Routes>
36
</div>
37
);
38
}
39
40
export default App;
41
What I had tried?
As I referred in stackoverflow and also many other websites, integrated below methods.
- Added base url inside package.json file
"homepage": "/app",
- Tried to pass the tag
<base href="http://myapp.com/app">
within<head>
tag in public/index.html page - Passed the base url within BrowserRouter in index.js
<BrowserRouter basename="app"> </BrowserRouter>
I am sure I am missing something, it would be great learning if someone help on this or give insights on this.
Thank you
Advertisement
Answer
I don’t know the correct answer to this , but I believe that you can redirect the route “/” to “/app” . I hope this can help you