Learn how to apply the idea of recursion to simplify your React component rendering.
<ul>
list based on this data structure.
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.
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
.