Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit form from a button outside that component in React?

Tags:

reactjs

I have a form in one of my React components, and and in the outside component that calls it I want to pass a reference to a button there, so that I can also submit that using that button.

To make it more clear I have the following:

import React, { Component } from "react"; import ReactDOM from "react-dom";  class CustomForm extends Component {   render() {     return (       <form onSubmit={alert('Form submitted!')}>         <button type='submit'>Inside Custom</button>       </form>     );   } }  function App() {   return (     <div>       <CustomForm />       <button>In Root</button>     </div>   ); }  const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); 

Now, I can submit the form using the button titled 'Inside Custom', but I also want to be able to submit the form using the button titled 'In Root' that is located in the root component. Is there a way to somehow pass reference from that button to that custom component, and actually submit the form when In Root button is clicked?

like image 535
tinker Avatar asked Sep 30 '18 10:09

tinker


People also ask

Can a button outside a form submit the form?

You can tie a submit button to a form that the button doesn't live inside of. The trick is to give the form an id and then reference that id with the button's form property. With this setup, clicking the Submit button will cause the form to be submitted.


1 Answers

You can achieve this by using regular HTML capabilities (HTML form Attribute), no need to use the React hacks:

Add "id" attribute to your form: id='my-form'

class CustomForm extends Component {     render() {         return (              <form id='my-form' onSubmit={alert('Form submitted!')}>                 // Form Inputs go here                  </form>         );     } } 

Then add the same Id to the "form" attribute of the target button outside of the form:

<button form='my-form' type="submit">Outside Button</button> 

Now, the 'Outside Button' button will be absolutely equivalent as if it is inside the form.

Note: This is not supported by IE11.

like image 198
Pavlo Kyrylenko Avatar answered Sep 20 '22 06:09

Pavlo Kyrylenko