Reputation: 61
I have an app built in react and I am trying to implement re-direct where I need to redirect the user from my app base URL to a completely new domain.
Example:
React app base URL - "localhost:3001" Redirect to - "www.google.com"
I am using react routes in my app.
ReactDOM.render( (
If I use Redirect as above, it redirects to "http://localhost:3001/#/http:/www.google.com"
How to get rid of base URL while redirecting to a new domain?
Upvotes: 4
Views: 7627
Reputation: 83
Expanding on an excellent answer by Facino La Rocca
import React, {Component} from 'react';
class DomainUrlRedirect extends Component{
componentDidMount(){
const{searchParams, pathname, url} = this.props
let uri = new URL(url);
uri.pathname = pathname
for(const paramName in searchParams){
uri.searchParams.append(paramName, searchParams[paramName])
}
window.location.assign(uri.href)
}
render(){
return(<span data-test-component="DomainUrlRedirect"></span>)
}
}
export default DomainUrlRedirect
You can leverage URL utility supported by modern browsers to construct your URL properly.
Also, don't forget that the component will still try to render. Render it as part of some other component on condition so that object that uses it does not disappear.
render(){
const{ redirectNow } = this.props;
return(<div>
<p>Important content</p>
{redirectNow &&
<DomainUrlRedirect {...url_params}/>
}
</div>)
}
Upvotes: 1
Reputation: 3866
React-route only allows redirect to other routes, you can confirm this by reading Github issue here
So the answer is NO, YOU CAN'T.
If I'm not misunderstanding your intention here, you want to redirect whatever which is not being handled by the router.
One aproach that comes to my mind as a solution:
A component-dedicated: Create a component dedicated for this route with a componentDidMount
similar to this:
componentDidMount() {
window.location.assign('http://github.com');
}
As an alternative, you can catch it directly in the server and redirect there.
But definitively you need to look for an alternative solutoin due react-route
does not allow redirecting to externals url
Upvotes: 11