Clara Daia
Clara Daia

Reputation: 159

How can I redirect to an absolute path with react-router v4?

I have a huge Django web app, with one of it's modules (a 'dashboard') written with node and react. User login is handled by a Django module.

The user should be logged into the main app in order to access the react dashboard, and this works partially - the code gets the user session from the browser and only renders stuff if there is one.

I would like now to redirect the user to the main app login page if there is no session, but I don't know how to do it with my current structure (and this bloody v4 router).

I am using a basename in the BrowserRouter component to use routes relative to the dashboard path in the django app.

This is what I came up with for the JSX for app.jsx:

<BrowserRouter basename='/en/dashboard'>
    {this.state.isAuthenticated ? (
        <Paper zDepth={0} style={{ height: '100%', backgroundColor: grey900 }}>
            <div style={{height: '100%'}}>
                <Header />
                <Switch>
                    <Route exact={true} path='/' component={FirstSection}/>
                    <Route path='/first' component={FirstSection}/>
                    <Route path='/second' component={SecondSection}/>
                </Switch>
            </div>
        </Paper>
    ) : (
        <Redirect to="/en/login"/>
    )}
</BrowserRouter>

However, it actually redirects to en/dashboard/en/login. I believe I could remove the 'basename' property from the BrowserRouter and add it to each subsequent Route, but if this module eventually grows bigger, it would make routing harder. Is there a better way to do this?

Upvotes: 8

Views: 25086

Answers (4)

duhaime
duhaime

Reputation: 27574

I ended up here because I wanted to use:

import { useHistory } from "react-router-dom";

const history = useHistory();
const response = getApiResponse();
if (response.condition) history.push(response.url);

The trouble was the url I got from the API was a fully qualified url ("http://wow.com/yeet"), and react router was prepending the host to the url ("http://wow.com/http://wow.com/yeet").

The fix was just to remove the host from the url to which the client redirected:

import { useHistory } from "react-router-dom";

const history = useHistory();
const response = getApiResponse();
const url = response.url.replace(window.location.origin, "");
if (response.condition) history.push(url);

Upvotes: 0

andruso
andruso

Reputation: 1975

You can do it without react router:

window.location.pathname = '/en/login';

Navigating away to a different site is using:

window.location.href = 'https://stackoverflow.com';

Upvotes: 2

Davo
Davo

Reputation: 986

As mentioned in Kyle's answer, there is no way to have to use absolute urls or to ignore the basename; however, if you want or "need" to run the redirection from the render method of your component you can create your own ultra-light "absolute redirect" component, here's mine:

import React from 'react'

class AbsoluteRedirect extends React.Component {

    constructor(props){
        super(props)
    }

    componentDidMount(){
        window.location = this.props.to
    }

    render(){
        return null
    }

}

export default AbsoluteRedirect

And then use it other components with a condition so it only gets mounted when your validation is true.

render(){ 

    if( shouldRedirect )
        return <AbsoluteRedirect to={ anotherWebsiteURL } />

    ...

}

Hope this helps :)

Upvotes: 2

Kyle Richardson
Kyle Richardson

Reputation: 5645

Unfortunately this isn't possible. If you're using a basename it will be added to base of every path before the href is created. This happens in the history module in createBrowserHistory in the push and replace methods which use the following function:

var createHref = function createHref(location) {
    return basename + (0, _PathUtils.createPath)(location);
};

uses either push or replace method.

You can find the following block of code in the Redirect.prototype.perform method:

if (push) {
  history.push(to);
} else {
  history.replace(to);
}

The above can be found in Redirect.js in the react-router module which is what the react-router-dom module imports and then exports.

To do what you're trying to do I would make the basename a const and added it to the front of your path in each of your routes.

It's unfortunate there is not an ignoreBasename option for a <Route /> or <Redirect />, though it is implementable.

Upvotes: 7

Related Questions