1

I have a React Search Bar and I'm trying to prevent a form submission or re render if a user clicks enter.

I read up on react synthetic events and applied that logic to both an obSubmit handler for the form element and the input element, neither one is working when applied individually to each element or when applied to both and I'm not sure why.

Expected behavior: If a user clicks enter nothing will happen, no clearing of the input text or form submission

Current behavior: User clicks enter, text field is cleared and form is submitted triggering a re render

Here's a snapshot of my current Component:

  const handleSubmit = event => {
    event.preventDefault();
  };

return (
    <form onSubmit={handleSubmit}>
      <StyledInput className={"inputWithIcon"}>
        <Input
          type="text"
          value={text}
          onChange={handleChange}
          placeholder="Search"
          onSubmit={e => {
            e.preventDefault();
          }}
        />
        <div className="left-icon">
          <svg viewBox="0 0 24 24" width="36px" height="36px">
             ...
          </svg>
        </div>

        <button className="right-icon" onClick={clearInput}>
          <svg width="24pt" height="24pt" viewBox="0 0 24 24" version="1.1">
             ...
          </svg>
        </button>
      </StyledInput>
    </form>
)

And a CodeSandbox demonstrating the issue:

Edit dreamy-nightingale-x8uwe

1 Answer 1

1

You need to add type="button" to your clear button. What's happening is that that button is being interpreted as the submit button, so when you hit enter, it's triggering your clearInput function.

<button className="right-icon" type="button" onClick={clearInput}> should solve your clearing problem.

Passing an onSubmit to the form will make it respond to any enter press. If you want to keep that, but avoid submitting on enter, you'll have to add a guard to the handleSubmit function.

The alternative would be wrapping everything in a normal div and adding handleSubmit only to the element you want responsible for submitting the form.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it, and this helped me recognize the "gotcha" with buttons and their types. Thanks so much for the help and clarity!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.