You can use the MutationObserver API to listen for changes to a React list component. The following code demonstrates how to use a MutationObserver to detect when the contents of a list component changes:
index.tsx712 chars33 lines
In the componentDidMount
lifecycle method, we create a new instance of a MutationObserver, passing in a callback function to handle mutations to the list component. We then call the observe
method on the observer instance, passing in the ref
to the list component and an options object that specifies that we want to observe changes to its children.
In the componentWillUnmount
lifecycle method, we make sure to call the disconnect
method on the observer to terminate the observation.
Finally, we render the list component, using the ref
we created earlier to capture a reference to the underlying DOM node. Anytime a mutation occurs to the list component, the callback function specified in handleMutations
will be executed.
gistlibby LogSnag