Docs · OSMD 3.0
OSMD in React
One effect does it all: create OSMD for the element, load and render, and destroy it in the cleanup.
import { useEffect, useRef } from 'react';
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';
export function ScoreView({ url }) {
const container = useRef(null);
useEffect(() => {
const osmd = new OpenSheetMusicDisplay(container.current);
osmd
.load(url)
.then(() => osmd.render())
.catch((error) => {
// AbortError: url changed, or the component unmounted, before the file arrived
if (error.name !== 'AbortError') console.error(error);
});
return () => osmd.destroy();
}, [url]);
return <div ref={container} />;
}
Use it like any component: <ScoreView url="/scores/my-score.musicxml" />. When url changes, React runs the cleanup first, which destroys the old instance, and then the effect again with a new one.
What destroy() does
osmd.destroy() is new in OSMD 3.0, made for components. It aborts a load() still in flight, releases the loaded score, removes OSMD’s resize observer, takes OSMD’s pages and cursor out of the element and ends the instance. Anything of yours inside the element stays. Our CI mounts this component in StrictMode, switches it to a second score and unmounts it, then checks that every OSMD instance it made is destroyed and no OSMD element is left on the page.
StrictMode and the catch
In development, StrictMode runs every effect twice: mount, cleanup, mount. The first instance is destroyed before its file arrives, so its load() is rejected with an AbortError, and the catch lets that one pass. A url that changes while a file is still loading ends the same way. Up to OSMD 2.3.1, the second mount could leave two scores in the same element; 3.0’s render() removes the pages a previous instance left there.
Resizing
With autoResize on (the default), OSMD 3.0 watches the element’s width with a ResizeObserver and lays the score out again 200 ms after the width stopped changing. Only the width counts, so a phone’s address bar sliding in and out doesn’t redraw the score. A render() while the element is hidden (a tab that isn’t shown, display: none) is skipped, and the score is drawn once the element has a width.
Next.js
The component uses hooks, so in the App Router its file needs 'use client' at the top. Effects don’t run on the server, and importing OSMD there is safe: it touches the DOM only when you create an instance.
On OSMD 2.3.1
Before 3.0 there is no destroy(). On 2.3.1, dispose() comes closest: it removes OSMD’s listeners, but leaves the drawing in the element.
Next: OSMD in Vue