user1941537
user1941537

Reputation: 6675

React Hooks - Start search when I click on Enter

In the following example:

import React, { useState } from 'react';

function App() {
  const [userQuery, setUserQuery] = useState('');

  const searchUserQuery = (e) => {
    window.open(`http://google.com/search?q=${userQuery}`);
  };

  return (
    <div className='App'>
      <div className='form'>
        <input
          type='text'
          value={userQuery}
          onChange={(e) => setUserQuery(e.target.value)}
        />
        <button onClick={searchUserQuery}>Google Search</button>
      </div>
    </div>
  );
}

export default App;

Once I click on the Button, a new browser tab opens with Google and shows the search result.

However, it works only if I click the button. If I write something in the input and hit the Enter key on my keyboard, nothing happens.

Isn't it that in a form pressing the Enter key should trigger the form? How could I modify my code, so that pressing the Enter key, starts the process?

Upvotes: 0

Views: 2383

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You should be using form element and onSubmit event. Here's what you'll go with:

import React, { useState } from 'react';

function App() {
  const [userQuery, setUserQuery] = useState('');

  const searchUserQuery = (e) => {
    e.preventDefault()
    window.open(`http://google.com/search?q=${userQuery}`);
  };

  return (
    <div className='App'>
      <form className='form' onSubmit={searchUserQuery}>
        <input
          type='text'
          value={userQuery}
          onChange={(e) => setUserQuery(e.target.value)}
        />
        <button type="submit">Google Search</button>
      </form>
    </div>
  );
}

export default App;

Upvotes: 1

Related Questions