Inspecting the data
<ul> list based on this data structure.
List rendering
Looking at the data we might do something like this.renderChildren method, so lets just use that instead.
renderChildren return is pretty much the same. That is because they are! And we already had a renderChildren method, it was just called List. So why not use it, now we can refine this component even further.
Recursion is where a function being defined is applied within its own logic.We are utilising the
List function in the same function that we are using it. This will allow you to infinitely nest children in this list and it will just keep nesting the different lists.
This example does assume that the nested list items follow the same data structure as the root list. This will obviously change depending on the requirements of the project but the benefit of using your React components as the recursive function is pretty powerful.
Want something a bit more “advanced”
Here is a bit more of a real-world example. We have some data to render different learning areas that you will find at a school, Math, English etc. This list has a similar structure to the list above but we have another requirement. We have a top level search input to filter the areas. While rendering, if any item contains a match with this filter it should show. For parent items, if any child items are visible, we should show the parent. Check out a working example. Lets define the rendering of a single Learning area. The data structure looks like this;level prop to component to help us indent the component.
filter value. We could set up the filter to have been created and stored within Context.
Listing component takes in our data and starts the recursive looping of our learning areas. But now, we have to work on that filtering requirement. Luckily, we will just need to stay within the LearningArea component.
<App /> and <DiffApp /> in the index.tsx to see the difference between the two.
We also added in another method called checkNestedChildrenMatch which once again uses recursion to check deeply nested children and ensure that all parents are visible as needed.
Now, this component can be cleaned up. For example, the indented padding can be replaced with styling, as well as the display styling. Other than that, I would say that was a success, and personally, might be a bit easier to read to the code in App.tsx.