Is it possible to define default route in react-router?
P粉128563140
P粉128563140 2023-08-27 17:06:31
0
2
501
<p>Suppose my app's base URL is <em>example.com/app</em></p> <p>Is it possible to set up basic routing in react-router instead of writing all routes as </p> <pre class="brush:php;toolbar:false;">/app/a /app/b /app/c</pre> <p>I can specify them as </p> <pre class="brush:php;toolbar:false;">a b c</pre> <p>I tried the following example found in the documentation but it doesn't work (the page won't display anything). Maybe it's because I'm using react-router@3.0.0-alpha.1 or I'm doing something wrong. </p> <pre class="brush:php;toolbar:false;">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> )</pre> <p><br /></p>
P粉128563140
P粉128563140

reply all(2)
P粉087074897

If you want to use , it gives you access to the history object, allowing you to change the page via history.push('/my-path') code> directly Method from js. You will face the problem that BrowserRouter has no history property available, and Router has no basename available.

The solution is as follows:

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>;
}

https://reacttraining.com/react-router/web/ api/BrowserRouter/basename-string

P粉647449444

Using the latest react router (v4) you can do this easily

<BrowserRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</BrowserRouter>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template