I'm running an SPA without the help of a 3rd party router. I want to redirect to an external URL within a function.
Obviously href and installing routers do not solve my problem.
I'm running an SPA without the help of a 3rd party router. I want to redirect to an external URL within a function.
Obviously href and installing routers do not solve my problem.
If you want to redirect to an external URL and not something internal, then it's easier. You get hold of the window.location object and you can make it possible. I can understand why <a href> will not be a right choice to do it programmatically.
The below works perfectly fine. I used a setTimeout to simulate a programmatic redirect.
class App extends React.Component {
componentDidMount() {
setTimeout(() => {
window.location.href = 'https://praveen.science/';
}, 1000);
}
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>