I recently wrote a blog post that mentions how to call methods in the parent component from a child component.
This post is similar but the difference is that we are going to be handling the onSubmit event that is fired when submitting a form.
Scenario
Suppose that you have the main App component, and within it you are have an imbedded Login component.
We are going to keep things simple for this example. In the App.js, we are going to place the Login component:
<Login></Login>
In the Login
component, let’s define a form that has one input field and one button:
import React, { Component } from 'react'
export class Login extends Component {
constructor(props){
super(props);
this.state = {
title: ''
}
}
onChanged = ({target}) => {
this.setState({
[target.name]: target.value
});
}
onSubmit = (e) => {
e.preventDefault();
this.props.loginRequest(this.state.title);
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="text" name="title" value={this.state.title} onChange={this.onChanged}></input>
<input type="submit" value="Submit" className="btn" />
</form>
)
}
}
export default Login;
This component has a simple form, defines state with one property, handles the onChanged
event and also the onSubmit
event. In the render method, there is a simple form.
The main thing to note is the onSubmit
event handler, which then calls a method in the parent component using this.props.loginRequest
.
In the App component, simply handle the incoming invocation:
<Login loginRequest={this.loginRequest}></Login>
Also define the mentioned method loginRequest which is going to handle the event:
loginRequest = (incoming) => {
console.log('Login request received: ' + incoming);
}
Now when you click on the Submit button, the onSubmit
event handler is going to be invoked which is going to call the loginRequest
method in App.js
.
Using React Router
In case you have defined a route using the React Router and want to invoke the parent component, add the same event handler but in the Route:
<Router>
<Route path='/login' render={(props) => <Login loginRequest={this.loginRequest}/>}/>
</Router>