Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a base route in react-router

Tags:

react-router

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> ) 
like image 690
galki Avatar asked Jul 05 '16 06:07

galki


People also ask

How do I set a default route in react router?

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!

What is a base route?

: the area between the bases of a baseball field used by a base runner.


Video Answer


2 Answers

With the newest react router (v4) you can easily do this

<BrowserRouter basename="/calendar">   <Link to="/today"/> // renders <a href="/calendar/today"> </BrowserRouter> 
like image 137
galki Avatar answered Sep 28 '22 02:09

galki


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

like image 39
Ambroise Rabier Avatar answered Sep 28 '22 03:09

Ambroise Rabier