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",