5

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.

2
  • 2
    Any sample code? Coz routers are needed for routing the views. Commented May 9, 2019 at 11:54
  • It does not look like a redirect to me. Just a plain set window.location.href will do. Commented May 9, 2019 at 11:58

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@AnkitVerma Yep. It does. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.