Home > Enterprise >  Submit form from sibling element in React
Submit form from sibling element in React

Time:11-08

I am trying to use a library but a submit button would be rendered outside of the form automatically (because body of the library's component is rendered as a sibling of the footer where the submit button should go). Is there a way to bind to this form so that the button that is outside of the form can trigger the form submit? Basically I want the button that is outside of the form to be able to act like it is inside the form. Is this possible?

Edit: I am using the Dialog component from the PrimeReact library. The button is in the JSX sent into the "footer" prop

rendered html

CodePudding user response:

The button's form attribute allows you to set the form that the button belongs to to achieve this behavior

<form action="/action_page.php" method="get" id="form1">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname">
</form>

<button type="submit" form="form1" value="Submit">Submit</button> 

https://www.w3schools.com/tags/att_button_form.asp

CodePudding user response:

If you're using React, you can use a ref and then dispatch an event.

The issue with using form.submit() or the form attribute is that your submit function will not be run since an event is not raised.

function App() {
  const formRef = React.useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('form submit fired');
  };

  return (
    <div>
      <form onSubmit={handleSubmit} ref={formRef}>
        {/* form stuff here */}
      </form>
      <button onClick={() => formRef.current.dispatchEvent(
        new Event('submit', { cancelable: true, bubbles: true })
      )}>
        Submit
      </button>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
body {
  text-align: center;
}

form {
  background: #eee;
  padding: 1rem;
  margin: 1rem;
}

form::before {
  content: 'your form here';
}
<div id='root'></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

  • Related