Skip to content
Advertisement

How to use and different options with element to redirect to an external website

I am trying to implement a list of options using <form> and <select>. Researching on the web, I notice that this is used to redirect to sections of the same website, but I want to make it work so that the user display the options and when they click on submit it redirects them to an external website.

import React from 'react'; 

export default function App() {  
  function handleChange(value) {
    // Do some stuff
  }

  return (
        
       /* what i have tried using onChange */ 
        <form >
          <select value={data} onChange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
         
          <option value="https://www.example.com">example</option>
          <option value="https://www.example.com">example</option>
          <option value="https://www.example.com">example</option> 
        
         </select>
         <input type="submit" value="Submit"/>
       </form>
       /*      */
  )
}   

Can I include inside some element like <option>"onChange method to_redirect='www.google.com'"</option> or what other way could make the website redirect users?

Advertisement

Answer

Navigating outside your application has nothing to do with react-router.

  1. Store the selection in a state variable
  2. On submit, use window.location to navigate to the chosen option
import { useState } from "react";

const options = [
  { value: "https://example.com/", label: "example" },
  { value: "https://example.com/", label: "example" },
  { value: "https://example.com/", label: "example" }
];

export default function App() {
  const [url, setUrl] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    window.location = url;
  };

  const handleChange = (e) => {
    setUrl(e.target.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <select required onChange={handleChange} defaultValue="">
        <option disabled hidden value="">
          Select a destination
        </option>
        {options.map(({ value, label }, i) => (
          <option key={i} value={value}>
            {label}
          </option>
        ))}
      </select>
      <button type="submit">Submit</button>
    </form>
  );
}

Edit white-https-50m320

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement