Josh
Josh

Reputation: 1235

React input component trying to use e.preventdefault() to prevent form submission, setting it on input and form both not working

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

Upvotes: 1

Views: 1807

Answers (1)

mindlis
mindlis

Reputation: 1677

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.

Upvotes: 1

Related Questions