โ๐ป Conditional Rendering
To render or not to render?
Suppose we want to render the persons data conditionally, say on the click of a button that toggles the data.
Instead of manually adding multiple <Person />
components to our app, we can use array methods to output a list of <Persons />
components.
In the same code where we rendered the content conditionally, i.e, conditionalPersons
:
Virtual DOM
React has a feature where it compares the current DOM with a virtual DOM, which is a visualization of what would be rendered in the future, compared to the changes that could be made in the past DOM.
In lists, it needs to be known which exact elements change. By default, this will render the whole list. For very large list of components, this is an inefficient way.
Hence we need to assign a "key" property to each child in the list so that React can keep track of each individual element inside the list, so that it can compare the different elements and only render those to the actual DOM, which have actually changed, and not the whole list.
Example:
NOTE: We can always use the index of the array as key, but it is better to use a separate property called id
so that it is easier for us as well to identify the element in the list.
The id
being linked to key
in the list when it is conditionally being rendered, is better for react to keep track of which element in the list needs re-rendering based on the comparison of the actual and the virtual DOM.
The deletePersonsHandler
is an eventHandler
that deletes the item from the list when it is clicked. This is in turn also removed from the state.
Flexible List
In the below example, we will be changing the name of the Person
component using another eventHandler
that will work only when it matches with the id
of that particular person, where we are renaming it, i.e, in the text field of that Person
component:
With this, we have a truly flexible component, which renders content conditionally, and only that component from the list whose state change, is re-rendered, with the key
property linked to the list element.
NOTE: To get the event
object from the place where the changes to the component happens, we need to define the event as an anonymous function's prop, like so:
Last updated