Search code examples
reactjsreact-routerreact-dom

There is a better way to redirect from a url to another in ReactJS?


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.


Solution

  • 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.