# Mutation Observer [component-header:sl-mutation-observer] The Mutation Observer component offers a thin, declarative interface to the [`MutationObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). The mutation observer will report changes to the content it wraps through the `sl-mutation` event. When emitted, a collection of [MutationRecord](https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord) objects will be attached to `event.detail` that contains information about how it changed. ```html preview
Click to mutate
👆 Click the button and watch the console
``` ```jsx react import { useState } from 'react'; import { SlButton, SlMutationObserver } from '@shoelace-style/shoelace/dist/react'; const css = ` .resize-observer-overview div { display: flex; border: solid 2px var(--sl-input-border-color); align-items: center; justify-content: center; text-align: center; padding: 4rem 2rem; } `; const variants = ['primary', 'success', 'neutral', 'warning', 'danger']; let clicks = 0; const App = () => { const [variant, setVariant] = useState('primary'); function handleClick() { clicks++; setVariant(variants[clicks % variants.length]); } return ( <> console.log(event.detail)}> Click to mutate ); }; ``` ?> When you create a mutation observer, you must indicate what changes it should respond to by including at least one of `attr`, `child-list`, or `char-data`. If you don't specify at least one of these attributes, no mutation events will be emitted. ## Examples ### Child List Use the `child-list` attribute to watch for new child elements that are added or removed. ```html preview
Add button
👆 Add and remove buttons and watch the console
``` ```jsx react import { useState } from 'react'; import { SlButton, SlMutationObserver } from '@shoelace-style/shoelace/dist/react'; const css = ` .mutation-child-list .buttons { display: flex; gap: .25rem; flex-wrap: wrap; margin-bottom: 1rem; } `; let buttonCount = 0; const App = () => { const [buttonIds, setButtonIds] = useState([]); function addButton() { setButtonIds([...buttonIds, ++buttonCount]); } function removeButton(id) { setButtonIds(buttonIds.filter(i => i !== id)); } return ( <>
console.log(event.detail)}>
Add button {buttonIds.map(id => ( removeButton(id)}> {id} ))}
👆 Add and remove buttons and watch the console ); }; ``` [component-metadata:sl-mutation-observer]