we have previously seen how to pass data from parent component to child component. In this article, we will see how to pass data from child component to parent component.
For this, we pass functions as props in React component.
Let’s create a new react application. Delete all the files from src folder EXCEPT index.js. Create a new file SearchBar.js in src folder.
index.js
Replace the existing code with below code
import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './SearchBar'
class App extends React.Component {
// defining state
state = { name: '' };
render() {
return (
<div>
<SearchBar onNameSubmit={this.onSearchSubmit}/>
</div>
);
}
onSearchSubmit(userName){
console.log(userName);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
SearchBar onNameSubmit={this.onSearchSubmit}
This statement will pass function as prop to the Child Component, SearchBar
SearchBar.js
Paste the below code in this file
import React from 'react';
class SearchBar extends React.Component {
constructor(){
super();
this.state = { name: '' };
this.onFormSubmit=this.onFormSubmit.bind(this);
}
onFormSubmit(event) {
event.preventDefault();
this.props.onNameSubmit(this.state.name);
}
render() {
return (
<div className="ui segment">
<form className="ui form" onSubmit={this.onFormSubmit}>
<div className="field">
<label>Enter your name</label>
<input type="text" value={this.state.name} onChange={(e) => this.setState({ name: e.target.value })} />
</div>
</form>
</div>
);
}
}
export default SearchBar;
this.props.onNameSubmit(this.state.name); This piece of code will pass the value from child component to parent component using functions in props.
Below is the output of above code
Type your name or anything else in the textbox, press enter. You can see the value you types in console.
