React Forms - Proper way to Network Request

Published on
3 mins read
––– views

We have the below, performSearch function will make a network request when the user clicks on the Find! button. Pretty typical, right? Network request will be made, some states will be updated and we will get a result.

function SearchBar({ performSearch }) {
  const [query, setQuery] = React.useState('')

  return (
    <div className="search-bar">
      <input
        type="text"
        value={query}
        onChange={(event) => {
          setQuery(event.target.value)
        }}
      />
      <button>Find!</button>
    </div>
  )
}

How would you implement the submit functionality to this from? You may think this is good enough.

<button onClick={() => performSearch(setQuery)}>Find!</button>

It will work, but I rarely hit the submit button with my mouse. I like using the enter key. No matter how great your workflow is, there is always a user that will ruin it.

Never trust your users, never assume the user will figure out how to use your app. Have trust issues, and be proud of it.

Adding onKeyDown and adding an if statement that checks the pressed is enter can solve this, but it isn't necessary and we cannot think of every single way that user can interact with the system.

onKeyDown={event => {
    if (event.key === 'Enter') {
      performSearch(query);
    }

Form will fix this

using <form> will listen to clicks and keys. So, we don't need to write different types of listeners. It keeps the code shorter, fool proof and easy to maintain. Using form for the submit event is the proper way.

 <form
      className="searchForm"
      onSubmit={event => {
        // will talk about this soon.
        event.preventDefault();
        performSearch(query);
      }}
    >
     <input
        type="text"
        value={query}
        onChange={(event) => {
          setQuery(event.target.value)
        }}
      />

HTML Forms VS React Forms

Typical HTML form will refresh the page after the submission, sometimes they direct you to a new page stating 'we received your request, thanks. etc etc`

Typical React form will not reload the page after submission. It can manage state of some inputs, like clear the fields and show some kind of message next to submit button saying "your message has been sent" and such but the current webpage won't reload.

To do that, we need to use event.preventDefault(). Default is to reload after submission, that's how HTML pages work.