search

Home  >  Q&A  >  body text

Is it possible to define default route in react-router?

<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粉128563140P粉128563140456 days ago489

reply all(2)I'll reply

  • P粉087074897

    P粉0870748972023-08-28 16:11:51

    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

    reply
    0
  • P粉647449444

    P粉6474494442023-08-28 00:10:44

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

    <BrowserRouter basename="/calendar">
      <Link to="/today"/> // renders <a href="/calendar/today">
    </BrowserRouter>

    reply
    0
  • Cancelreply