简体   繁体   中英

How to make form not refresh with custom submit button in React

im using react and i try to make form with custom submit button (with div) but when i submit the form the page automatically refreshes, despite e.preventDefault my code :

 <form onSubmit={e => e.preventDefault()} className="form">
        <div
          onClick={e => {
            e.preventDefault();
            document.querySelector(".form").submit();
          }}
          id="button"
        >
          Submit
        </div>
      </form>

demo on code sandbox : https://codesandbox.io/s/bitter-pond-9fcnr

As per the spec

form . submit()

Submits the form, bypassing interactive constraint validation and without firing a submit event .

This is why your onSubmit callback doesn't get called, and page is getting refreshed as per the normal browser behaviour.

I'd suggest a work around in this case:

import React, { useRef } from "react";
import ReactDOM from "react-dom";


function App() {
  const submitEl = useRef(null);
  const handleFormSubmit = e => {
    e.preventDefault();
  };

  const handleBtnClick = e => {
    e.preventDefault();
    submitEl.current.click();
  };

  return (
    <div className="App">
      <form onSubmit={handleFormSubmit} className="form">
        <div onClick={handleBtnClick} id="button">
          Submit
        </div>
        <input
          ref={submitEl}
          name="submit"
          type="submit"
          style={{ display: "none" }}
        />
      </form>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I came up with this solution but I don't know if it is the best idea:

  <form onSubmit={e => e.preventDefault()} >
        <div
          onClick={e => {
            e.preventDefault();
            document.querySelector(".hidden-button").click();
          }}
          id="button"
        >
          Submit
        </div>
        <button type="submit" id="hidden-button"/>
      </form>

and also in css :

#hidden-button{
      display: none;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM