0

I have a ReactJS application that requires modification.

Currently, a specific route displays a component.

    <Route
      exact
      path="/myroute"
      render={props => (
        <MyComponent
          {...props}
          action="myroute"
          landing={fetchParam(
            props.location.search,
            'service',
            process.env.REACT_APP_DEFAULT_SERVICE_PAGE
          )}
        />
      )}
    />

Now, I need to change the logic for this particular route:

I need to check certain parameters to redirect the user to an external page. Therefore, I no longer need to display anything for this specific route.

What is the best practice for achieving this? Is it possible to have a custom component where I can implement this logic without any rendering?

I tried in this way: I created a custom component for testing:

import React from 'react';
import { Redirect } from 'react-router-dom';

const CustomRedirectComponent = () => {
  const shouldRedirect = true; 

  if (shouldRedirect) {
    // Redirect the user to the external page
    return <Redirect to="https://www.external-page.com" />;
  } else {
    // Render any other components 
    return <div>Content for the specific route</div>;
  }
};

export default CustomRedirectComponent;

I defined a new Route for it:

<Router>
      <Switch>
        <Route exact path="/test" component={CustomRedirectComponent} />
      </Switch>
    </Router> 

In this way, I encountered an error/warning in the error console:

Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

On the page, there is a refresh without any redirect, and the current URL is replaced with:

https://my-domain/https://www.external-page.com

Instead, If I try to use directly:

window.location.href=myExternalPageUrl

this works fine..

Please note that I'm using:

"react-router-dom": "^4.3.1",

Safari
  • 11,437
  • 24
  • 91
  • 191

1 Answers1

0

Instead, If I try to use directly:

window.location.href=myExternalPageUrl

this works fine..

you would want to do something like this to avoid pushing to the history stack:

window.location.replace(myExternalPageUrl);

but yes this is the best way to redirect to an external site. If you use a <Redirect> component then react is going to have to do some rendering for that to be accomplished. In general it would be better to do this on the server before react ever gets engaged at all of course, but I understand in some cases this isn't possible in which case using window.location.replace is your best bet to make it happen as quick as possible.

Zachiah
  • 1,750
  • 7
  • 28
  • What is the correct way to manage redirects using window.location.href? I mean, if I have a component to handle the redirect logic, is it correct to have this redirect within the render method, or is it better to use a different approach? – Safari Aug 03 '23 at 13:20