Is there a better way to redirect from a URL to another in ReactJS?

If a user accesses "mysyte.com/app", I want to redirect to "mysyte.com/app/login" by changing the URL in the browser.

I managed to do it 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")
)

      

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

Thanks in advance.

+3


source to share


1 answer


You can use it Redirect

as a component directly like this:

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

      



Check out the documentation for this .

+4


source







All Articles