How to use async/await in React props

A new way for bi-directional communication between react components.

Mudafar El Halabi
Leniolabs_
2 min readMay 26, 2019

--

Given two react components Parent and Child, we want to find a way to communicate from the child to the parent and vice-versa.

Child to parent

This is pretty forward, we could simply pass an event handler/function from the parent to the child and let the child trigger it when needed:

Parent to child

Unlike the previous case, this one is a little bit cumbersome, to trigger child event from parent component we can use React Refs as follow:

Await Parent prop from Child

Let’s create a very simple TODO app with only two components:

  • Todo: with an input, a button to fetch todo and a div to show it
  • App: to fetch todo by id from jsonplaceholder rest API.

Todo is the child and App is the parent component.

Todo will have its internal state to store:

  • todo : an object with API JSON response.
  • todoId : an integer with input value.

It also will call and await the prop onFetchTodo from the parent, passing todoId as an argument as follow:

App will fetch the todo related to the passed todoId :

That’s it! A workable example is provided with the following codesandbox:

By using async/await props we can not only achieve a smooth bi-directional component communication, but also we can create a generic react component/library to handle the business logic and let the final user provide her own API and data handling (mapping/reducing).

--

--