DEV Community

Yahaya Kehinde
Yahaya Kehinde

Posted on

Passing Data From Child to Parent Components In React Using Call-Back Methods

In a previous post, we discussed how props are used to pass data in a unidirectional flow, meaning from parent to child components. However in this writeup, we will discuss how data is passed up the chain from child to parent using props. This allows data to climb up the chain and then finally invoke a callback method defined in the parent component.

Suppose we have two class components, a parent App component stored in App.js, and a SearchBar component stored in SearchBar.js, both in the same folder.

Now let’s assume the SearchBar component takes in a user’s search input in order to make an HTTP GET request to an API which is defined in the main App component. The main challenge now is getting the user’s input from the SearhBar component (the child component) up the chain to the main App component (parent component) where the data will be fetched using the Fetch API or Axios.

Consider the code sample below. In SearchBar.js, we have

Alt Text

In the code sample above, we first initialise a state object text and assign it to an empty string. Next we create an input tag and then add an onChange event handler in order to store every text entered by the user. We then attach a function handleChange to the onChange handler which we want to be invoked whenever the user enters a text and update this.setState with every input entered as e.target.value.

The next step is to then assign the value to this.state.text within the input tag. After this, we attach an onSubmit event handler to the form and also attach a function handleSubmit and within it add an e.preventDefault() in order to prevent the default submission of the form.

Alt Text

Now, within the App component in App.js

Alt Text

We import the SearchBar component and within it then we create a new state which we will name term and initialise it to an empty string "". We will add a new props to the rendered SearchBar component which can be named anything we like but which we will call getRequest and assign it a callback method which we will also name getRequest while using the async await syntax. This call back method is responsible for making the HTTP Request to our random number API.

Afterwards, we update our state object using this.setState within our callback method and update the value of the state to the response from our API call.

Alt Text

Finally within handleSubmit method in the Search Bar component, we then use the getRequest props and invoke it with the value stored in the updated state as this.props.getRequest(this.state.text)

Alt Text

With this, the users search input from the SearchBar component is passed to the parent component in order to make a request to the API

Top comments (0)