3

If a user access 'mysyte.com/app', I want to redirect him to 'mysyte.com/app/login' changing the url in the browser.

I've managed to do this with the following code:

import React    from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import Login from "./login/login"

ReactDOM.render(
    <BrowserRouter>
        <Switch>
            <Route path="/app/login" component={Login}/>
            <Route path="/app" render={ () => <Redirect push to="/app/login" /> } />
        </Switch>
    </BrowserRouter>,
    document.getElementById("app")
)

As I am in my first week of React, I'm wondering if there is a better way to do this.

Thanks in advance.

reinaldoluckman
  • 6,317
  • 8
  • 42
  • 50
  • 1
    See this as well https://stackoverflow.com/questions/44127739/trying-to-change-the-routing-url-based-on-a-specific-condition-in-react/44128108?lipi=urn%3Ali%3Apage%3Ad_flagship3_messaging%3BAraXqm6yS4%2BOyQqpdrg61w%3D%3D#44128108 – Shubham Khatri Jun 09 '17 at 16:56

1 Answers1

4

You should be able to use Redirect as a component directly like so:

<Switch>
  <Route path="/app/login" component={Login} />
  <Redirect from="/app" to="/app/login" push />
</Switch>

Check out the documentation for this.

reinaldoluckman
  • 6,317
  • 8
  • 42
  • 50
Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56