React — submit form using button in parent component II

Daneesha Bartholomeusz
2 min readOct 23, 2021

--

[Comment: Tested for React version 17.0.2]

I have a post here which describes how to submit a form in a child component with a button in a parent component. This article is outdated now as React changes so fast.

What I’m describing below is the modified version of the said post which works for recent versions of React.

When you declare the child component you should create the ref value in its constructor.

constructor(props) {
super(props);
this.myRef = React.createRef();
}

In the render function set the ref value on the element that you need to refer to.

<Form  ref={this.myRef}>

Here’s the method that should handle the button click event.

handleSubmit = (event)=> {
event.preventDefault();
//Your code here. For example,
alert( document.getElementById('name').value);
}

In the parent you should create a ref value in the constructor.

constructor(props) {
super(props);
this.childRef = React.createRef();
}

In the render method when you create the child you have to define the ref value.

<ChildComponent ref={this.childRef}/>

And the button has a onclick method.

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

In the click method you call the function you wrote in the child component.

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

Here is the complete Child.js file.

import React from 'react';
import { Form } from 'react-bootstrap';
class ChildComponent extends React.Component {constructor(props) {
super(props);
this.myRef = React.createRef();
}
handleSubmit = (event)=> {
event.preventDefault();
//Your code here. For example,
alert( document.getElementById('name').value);
}
render() {
return (
<div>
<Form ref={this.myRef}>
<input type="text" id="name" name="name" />
</Form>
</div>
);
}
}
export default ChildComponent;

Here is the complete parent.js file.

import React from 'react';
import ChildComponent from './Child';
import { Button } from 'react-bootstrap';
class ParentComponent extends React.Component { constructor(props) {
super(props);
this.childRef = React.createRef();
}
onClick = (event) => {
this.childRef.current.handleSubmit(event);
}
render() {
return (
<div>
<ChildComponent ref={this.childRef}/>
<Button variant= "light" onClick={this.onClick}>
Submit
</Button>
</div>
);
}
}
export default ParentComponent;

Here is the complete index.js file.

import React from 'react';
import ReactDOM from 'react-dom';
import ParentComponent from './Parent';
ReactDOM.render(
<React.StrictMode>
<ParentComponent />
</React.StrictMode>,
document.getElementById('root')
);

--

--