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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With