Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 344
reinaldoluckman Avatar asked Jan 23 '26 14:01

reinaldoluckman


1 Answers

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.

like image 118
Fabian Schultz Avatar answered Jan 26 '26 17:01

Fabian Schultz



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!