Pass data from child component to its parent in ReactJS
Steps:
1 min readJul 4, 2021
- In the parent component, create a callback function. This callback function will retrieve the data from the child component.
- Pass the callback function to the child as a prop from the parent component.
- The child component calls the parent callback function using props and passes the data to the parent component.
Implementation:
Parent: src/components/Contact.js
import React from 'react';
import Location from './Location';class Contact extends React.Component {
constructor( props ) {
super( props );
this.state = { location: null };
}handleCallback = ( childComponentLocation ) => {
this.setState({ location: childComponentLocation });
}render() {
return(
<div>
<Location parentCallback={this.handleCallback} />
{ this.state.location }
</div>
);
}
}export default Contact;
Child: src/components/Location.js
import React from 'react';class Location extends React.Component {onSubmitForm = ( event ) => {
this.props.parentCallback( event.target.location.value );
event.preventDefault();
}render() {
return (
<div>
<form onSubmit={this.onSubmitForm}>
<label>
Location:
<input type="text" name="location" />
</label>
<input type="submit" name="submit" value="submit" />
</form>
</div>
);
}
}export default Location;