use a mutation observer with a react list component in javascript

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.tsx
import React from 'react';

class ListComponent extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
  }

  componentDidMount() {
    this.observer = new MutationObserver(this.handleMutations);
    this.observer.observe(this.listRef.current, { childList: true });
  }

  componentWillUnmount() {
    this.observer.disconnect();
  }

  handleMutations = (mutationsList) => {
    console.log('List component changed!');
    // Do something in response to changes in the list component
  }

  render() {
    return (
      <ul ref={this.listRef}>
        {this.props.items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    );
  }
}
712 chars
33 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