Seven Lee
Seven Lee

Reputation: 627

React-router auto redirect any route to root "/" except for "/main"

I used react-router, even tried <Redirect .. />, I can't redirect to the /, the main problem is the / is out of the other routes, so I need to use <Redirect from="*" to="" />, it seems to not work.

then I also need to prevent /main redirecting to /, I put the <Redirect .. > after <Route component={MainView} path="main">

another requirement, how make the localhost:3000 to localhost:3000/ to use AppIndex IndexRoute

please check code below:

import MainView from 'components/MainView';
import ThemeIndex from 'components/ThemeIndex';
import AppIndex from 'components/ThemeIndex';
import Shop from 'components/Shop';
import App from 'components/App';

export default (
    <Route component={App} path="/">
      <IndexRoute component={AppIndex}></IndexRoute>
      <Route component={MainView} path="main">
        <IndexRoute component={ThemeIndex}></IndexRoute>
      </Route>
      <Redirect from="*" to="" />
    </Route>
);

have any idea?

Upvotes: 11

Views: 30207

Answers (2)

Nischith
Nischith

Reputation: 166

agree with what David said , this section in the React router Redirect docs briefs more clearly if there is any other use case :)

Upvotes: 0

David Guan
David Guan

Reputation: 4300

Instead of leaving to an empty string, you have to specify the path, which means <Redirect from="*" to="/" /> in this case.

To make the localhost:3000 to localhost:3000/, you don't have to do anything, your current code already get the job done. If you go to any website's root URL, Say http://stackoverflow.com, and try type location.pathname in console, you'll get "/"

Please ask me if you have any other problem.

Upvotes: 23

Related Questions