Inverse Data Flow in detail
The course is part of this learning path
This module looks at Inverse Data Flow in React
The objectives of this module are to provide you with an understanding of:
- Inverse Data Flow
This learning path is aimed at all who wish to learn how to use the ReactJS framework.
We welcome all feedback and suggestions - please contact us at firstname.lastname@example.org to let us know what you think.
So what's the state of play now? The state of searchText and advanced live in the FilterableCoursesTable. The values of searchText and advanced are updated in the SearchBar components. The SearchBar component receives these values as props and props are immutable. React only supports unidirectional data flow from the top of the component tree to the bottom. It appears we have a massive problem here. How do I get data from the SearchBar component back to the FilterableCoursesTable component to update it state? The answer is not as complicated as you might think. Thinking about it logically, we pass values as props from parent to child components. We saw it when we investigated prop types that functions can be props too. Here in lies the solution we need. We can pass a change handling function to update the state in the parent as a prop to child components. Passing a function as a prop means that it is executed in the component is declouding. We can just call it from somewhere else and in this case that somewhere is the SearchBar components. As we call it from the SearchBar component, we have access to the values in it, including rather conveniently for us, any events that are raised. Thus the values from the form can seemingly flow back up the tree. You can see that a handle change function has been added to the FilterableCoursesTable. And this is passed to the SearchBar as a prop. The function expects to receive an event works out which input fired it which is easy in our case is we only have two and there are different types. And sets the state accordingly using the value supplied with the event. The SearchBar receives this function as a prop and uses the handle change function as perhaps the unchanged event handling passing in the event. The rest of the execution is done in the parent. If you look at the component tab in the developer tools you can see the change has happened. The state is updated as we type in the text box and as we click in the checkbox, this also changes. The SearchBar receives this new state as props. And obviously the courses table receives that as well to help it filter. Although we've used this technique for form data, it can be done for any data in the application. It doesn't necessarily need to come from the user event. If you go on to look at state management there are some hooks and techniques that can make this easier in large applications.