The last and final feature we'll add to Minimum Viable React are keys. By keys, I refer to the key attribute that you should assign to components or simple elements when rendering lists.
The framework needs a way to know whether it should replace a component or update an existing one. So far, the decision has only been based on the type of the new virtual element and the existing component. Remember that if a virtual element represents a component, the type refers to the constructor of that component. This heuristic is insufficient when we want to render a list of components that all have the same type.
Here's a quick example of why we need keys. You might remember this app from part 3. I mentioned that the app has a bug. Let's look at that bug more closely now.
Try clicking the 'Show Logo' button for New York. Then, sort the list by the number of lines by clicking the header that says 'lines'. You'll see that the rows are now ordered by the number of lines, but the New York City Subway logo is hidden and the logo for Paris Métropolitain shows up instead. This happens because MVR has no way of knowing that Paris and New York should be two instances of the same component so it just updates each component with new props (New York becomes Paris). Keys provide that information.
In the past, we've just iterated through the children of each virtual element and diffed them against the DOM nodes at the same index.
Now, we'll replace this simple algorithm with a more complex one where we compare the keys of the elements. The code for this is pretty long so I'll try to give a good summary first. The steps are:
Iterate through the DOM elements we want to diff against and divide them into keyed and unkeyed elements.
Iterate through the virtual elements and treat keyed and unkeyed elements separately.
For keyed elements:
If a DOM element with the same key exists, move it to its correct position (index of the virtual element), and diff them as per usual. Otherwise, create a new DOM element.
For unkeyed elements:
Diff against the DOM element at the same index in the unkeyed DOM elements array. If a DOM element at that index doesn't exist, create a new DOM element.
Now, we can update the metro app to use keyed components and the bug is gone. Each component retains its state and the correct logos remain visible even after the list is sorted.
Support for keys was the last requirement for a ToDo app. So here it is: a ToDo app built with Minimum-Viable-React.
Congratulations if you've made it this far. This certainly was a much more elaborate undertaking than I first thought and I'm the first one to admit that I underestimated the complexity of the project. The final MVR framework is just shy of 500 lines of code, which is minuscule compared to React itself, but, obviously, we've only implemented a small subset of React's features. Although, I'd argue, the most important ones.
Check out the source code for MVR if you want to investigate further.