React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand,so follow these steps to figure it out:
For each piece of state in your application:
Identify every component that renders something based on that state.
Find a common owner component (a single component above all the components that need the state in the hierarchy).
Either the common owner or another component higher up in the hierarchy should own the state.
If you can’t find a component where it makes sense to own the state,create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
Let’s run through this strategy for our application:
ProductTable needs to filter the product list based on state and SearchBar needs to display the search text and checked state.
The common owner component is FilterableProductTable.
It conceptually makes sense for the filter text and checked value to live in FilterableProductTable
Cool,so we’ve decided that our state lives in FilterableProductTable. First,add a getInitialState() method to FilterableProductTable that returns {filterText: ”,inStockOnly: false} to reflect the initial state of your application. Then,pass filterText and inStockOnly to ProductTable and SearchBar as a prop. Finally,use these props to filter the rows in ProductTable and set the values of the form fields in SearchBar.
You can start seeing how your application will behave: set filterText to “ball” and refresh your app. You’ll see that the data table is updated correctly.
React makes this data flow explicit to make it easy to understand how your program works,but it does require a little more typing than traditional two-way data binding. React provides an add-on called ReactLink to make this pattern as convenient as two-way binding,but for the purpose of this post,we’ll keep everything explicit.
If you try to type or check the Box in the current version of the example,you’ll see that React ignores your input. This is intentional,as we’ve set the value prop of the input to always be equal to the state passed in from FilterableProductTable.
Let’s think about what we want to happen. We want to make sure that whenever the user changes the form,we update the state to reflect the user input. Since components should only update their own state,FilterableProductTable will pass a callback to SearchBar that will fire whenever the state should be updated. We can use the onChange event on the inputs to be notified of it. And the callback passed by FilterableProductTable will call setState(),and the app will be updated.
Though this sounds complex,it’s really just a few lines of code. And it’s really explicit how your data is flowing throughout the app.