Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from '/' in React-Router

Tags:

react-router

I trying setup redirect from "/account" to "/account/signIn"

  <Layout>
    <Switch>
      <Redirect from="/account" to="/account/signIn" />
      <Route path="/account/signIn" component={() => <div>signIn</div>} />
      <Route path="/account/signUp" component={() => <div>signUp</div>} />
    </Switch>
  </Layout>

When i go to http://localhost:3000/account/signUp i redirecting to http://localhost:3000/account/signIn. This problem is fixed in this way:

  <Layout>
    <Route exact path="/account" render={() => <Redirect to="/account/signIn" />} />
    <Route path="/account/signIn" component={() => <div>signIn</div>} />
    <Route path="/account/signUp" component={() => <div>signUp</div>} />
  </Layout>

But i think that is not best way, because i have a question this is bug or normal behaviour?

like image 622
Pavel Avatar asked Mar 02 '26 05:03

Pavel


1 Answers

The from on <Redirect> matches loosely by default. As you have it, it will match anything that starts with /account, which includes your /account/signIn and /account/signUp paths.

Inside of Switch, it's actually reading the props of its children directly and doesn't distinguish the type of component. So, you can use exact and strict like you can on a Route.

Therefore, this should work for you:

<Layout>
  <Switch>
    <Redirect exact from="/account" to="/account/signIn" />
    <Route path="/account/signIn" component={() => <div>signIn</div>} />
    <Route path="/account/signUp" component={() => <div>signUp</div>} />
  </Switch>
</Layout>
like image 149
Tim Dorr Avatar answered Mar 03 '26 22:03

Tim Dorr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!