Skip to content
Advertisement

React Form submits automatically, prevent automatic submission

I have a form which has a rich text editor and a form submit button, the rich text editor has style buttons which when clicked submit the form inputs (which is not desirable).

I want to prevent this behaviour I want the form to submit only when the submit button is clicked and not when the RTE style button is clicked.

Code:-

Form Code

Advertisement

Answer

I’ve moved the RichEditor out of the form. You can still handle the form submit, I’ve added the onClick listener on submit button itself. Just copy and paste this return statement in your App.js

return (
    <>
      <div>
        <form>
          <label htmlFor="contact">
            Full Name <span id="required-input-star">*</span>
          </label>
          <br />
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
          <br />
          <label htmlFor="contact">
            Email <span id="required-input-star">*</span>
          </label>
          <br />
          <input
            type="text"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />

          <br />
          <label htmlFor="description">
            Description <span id="required-input-star">*</span>
          </label>
          <br />
        </form> //closed the form here, and moved out RichEditor


       <RichTextEditor />

        <hr />
        <div className="frm-btn-container">
          <input type="submit" value="Cancel" id="cancel-btn" />
          <input type="submit" value="Create" onClick={onSubmit} />
        </div>
      </div>
    </>
  );
};


User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement