Solid

medium-zoom works with Solid out of the box. Wrap it in a small component, then use it like an <img>.

Install the package

Package manager
npm install medium-zoompnpm add medium-zoomyarn add medium-zoombun add medium-zoom

The standard import includes zoom styles and TypeScript definitions.

Create the component

Attach the zoom once the image is in the document, and detach it when the component is disposed:

solid
import mediumZoom, { type ZoomOptions } from 'medium-zoom'
import { onCleanup, onMount, splitProps, type JSX } from 'solid-js'

type ZoomableImageProps = JSX.ImgHTMLAttributes<HTMLImageElement> & {
  options?: ZoomOptions
}

export function ZoomableImage(props: ZoomableImageProps) {
  const [local, image] = splitProps(props, ['options'])
  let element!: HTMLImageElement

  onMount(() => {
    const zoom = mediumZoom(element, local.options)
    onCleanup(() => zoom.detach())
  })

  return <img ref={element} {...image} />
}

Save it as ZoomableImage.tsx. The component passes attributes such as src, alt, width, and height to the image.

Display an image

Import the component and give it the image attributes:

solid
import { ZoomableImage } from './ZoomableImage'

export function App() {
  return (
    <ZoomableImage
      src="/assets/images/ocean-sunset.jpg"
      alt="Ocean sunset"
      width="1920"
      height="1280"
    />
  )
}

Click the image to enlarge it:

Press Enter or Space to zoom. Click, press Escape, or scroll to close.

Click the enlarged image or its background, press Esc, or scroll to close the zoom.

Width and height reserve space while the image loads. To keep the image responsive, follow the image size step of the JavaScript quickstart.

Set options

Pass options to change the margin, background, or scroll behavior:

solid
<ZoomableImage
  src="/assets/images/ocean-sunset.jpg"
  alt="Ocean sunset"
  options={{ margin: 24, background: '#000000' }}
/>

The component reads its options when it mounts.

Server rendering

onMount() runs only in the browser, so the component also works with SolidStart server rendering. The server outputs the plain image, and the zoom attaches after hydration.

Next steps