Assuming my app's base url is example.com/app
Is it possible to set a base route in react-router so instead of writing all routes as
/app/a /app/b /app/c
I can just specify them as
a b c
I tried the below example I found in the docs but it wouldn't work (page would display nothing). Maybe it's because I'm using [email protected], or I'm doing something wrong.
import { useRouterHistory } from 'react-router' import { createHistory } from 'history' const history = useRouterHistory(createHistory)({ basename: '/app' }) const Root = ({store}) => ( <Provider store={store}> <Router history={history}> <Route path='/' component={App}> ... </Route> </Router> </Provider> )
Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!
: the area between the bases of a baseball field used by a base runner.
With the newest react router (v4) you can easily do this
<BrowserRouter basename="/calendar"> <Link to="/today"/> // renders <a href="/calendar/today"> </BrowserRouter>
If you want to use <Router />
, that give you access to history object, allowing you to change page through history.push('/my-path')
method directly from js. You will face the issue that BrowserRouter does not have history
prop available, and Router does not have basename
available.
The solution is the following:
const App: React.FC = () => { // do not put a slash at the end of the basename value. const history = createBrowserHistory({ basename: '/your-base-name' }); return <Router history={history}> ... </Router>; }
The base URL for all locations. If your app is served from a sub-directory on your server, you’ll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash
https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With