Home > Software engineering >  Take user input and onclick button it should load url according to input in new tab in react js
Take user input and onclick button it should load url according to input in new tab in react js

Time:11-08

I want to take city name as input and on button click it should call specific url https://www.google.com/maps/search/tourist places in mumbai with ending url with input value in react. It should open the url in new tab

Destination.jsx (file name)

import React from 'react'

const Destination = () => {
  
  return (
    <div>
     <h1>Destination</h1> 
     <input type="text" name="place"  id="place" placeholder="Enter place" />

     <button type="Submit" id="submit"> Search </button>
    </div>

  )
}

export default Destination

CodePudding user response:

You can do like this to search places in new tab.


import React from 'react';

const Destination = () => {
  const handleSearch = (e) => {
    window.open(
      `https://www.google.com/maps/search/tourist places in ${e.target.place.value}`,
      '_blank'
    );
  };

  return (
    <div>
      <h1>Destination</h1>
      <form onSubmit={handleSearch}>
        <input
          type="text"
          name="place"
          
          id="place"
          placeholder="Enter place"
        />

        <button type="Submit" id="submit">
          Search
        </button>
      </form>
    </div>
  );
};

export default Destination;


CodePudding user response:

Create a state:

const [destination, setDestination] = useState("");

Then use this state to populate your search query like this:

<input type="text" name="place"  id="place" placeholder="Enter place" value={destination} onChange={(e) => setDesitnation(e.target.value)} />

and then when you submit you can call a custom function on the onClick() of button:

<button id="submit" onClick={searchDestination}> Search </button>

The function might go somwthing like this:

const searchDestination = () => {
    window.location.href = `https://www.google.com/maps/search/tourist places in ${destination}`;
}
  • Related