React — submit form using button in parent component

--

[Edit: October 2021]

[Comment: This code works for earlier versions of React to the current versions. I have a post here which describes how to do this for latest versions of React (tested for React version 17.0.2) — React — Submit form using button in parent component II]

This is how I went about it.

You can give a ref to the child component when it is being created.

<ChildComponent ref={this.childComponent}/>

And use it in the button’s onClick method. (This is the code for the button)

<Button variant= "light" onClick={this.onClick}>  
Submit
</Button>

(This is the onClick method)

onClick = (event) => {
this.childComponent.current.handleSubmit(event);
}

I’m calling a method in the child component called handleSubmit. It can look like this.

handleSubmit = (event)=> {
event.preventDefault();
//Your code here. For example,
alert("Form submitted");
}

--

--