The data flow in React.js is always one-way and follows the top-down approach. That is, you can only pass states using props from parent to child component. However, there’s a way to pass a state from the child to the parent component using a callback method.
Here’s the App.js file for the functionality:
import "./styles.css";
import React from "react";
import TextInput from "./TextInput";
class App extends React.Component {
onSearchEnter(searchTerm) {
alert(`Entered text is: ${searchTerm}`);
}
render() {
return (
<div className="App">
<TextInput onSearchEnter={this.onSearchEnter} />
</div>
);
}
}
export default App;
Code language: JavaScript (javascript)
In the above file, you’d notice that I’ve passed in a function called onSearchEnter by referring to this.onSearchEnter on line 13. This function is capable of taking in a variable and alert it to the user as defined on line 6. Now, here’s the TextInput component, which I’ve actually used on line 13 above:
import React from "react";
class TextInput extends React.Component {
state = { searchText: "" };
onInputSubmit = (e) => {
if (e.key === "Enter") {
e.preventDefault();
this.props.onSearchEnter(this.state.searchText);
}
};
render() {
return (
<input
type="text"
placeholder="Enter text"
onKeyDown={this.onInputSubmit}
onChange={(e) => this.setState({ searchText: e.target.value })}
/>
);
}
}
export default TextInput;
Code language: JavaScript (javascript)
In the child component above, if the user presses the enter key, I’ve called the onSearchEnter function and passed in the search text from the state (line no 9). You’d notice that the parent component, App.js here, isn’t directly accessing the searchText state. Instead, it’s using the callback method to receive the value of the state.