Redirect to an External Link from your React Application

You can make use of window object for redirecting to an external URL from your application. Let us assume that you want to redirect users to a specific URL that has typed by that user. Consider the example given below.

import React, { useState } from 'react';

const App = () => {

  const [url, setUrl] = useState('')

  const changeHandle = e => {
    setUrl(e.target.value)
  }
  const submitHandle = e => {
    e.preventDefault()
    window.location.replace(`https://${url}`)
  }

    return (
      <div>
        <form onSubmit={submitHandle}>
          <input type="text" value={url} onChange={changeHandle}/>
          <button>{`Go to ${url}`}</button>
        </form>
      </div>
    );
}

export default App;

Here, we are replacing the current URL with the input received from the user. We can redirect to an external URL by simply using window.location.replace(url). The output of the given code will be as below.

Here, I given the input as facebook.com and button name also changed to the same. Clicking on the button will redirect to the facebook page as below.

Similar Posts

Leave a Reply