Skip to content

Instantly share code, notes, and snippets.

@robvanderleek
Last active April 27, 2024 18:27
Show Gist options
  • Save robvanderleek/d6cf78dc7d504a233a2f78a79e25b722 to your computer and use it in GitHub Desktop.
Save robvanderleek/d6cf78dc7d504a233a2f78a79e25b722 to your computer and use it in GitHub Desktop.
Play Asciinema recordings in React

Play Asciinema recordings in React

Asciinema is a great way to share and embed terminal recordings on the web.

Getting started with Asciinema on macOS is as simple as installing the tool with brew install asciinema, and creating a new recording with asciinema rec demo.cast.

There's an NPM package available if you want to embed the recoding on a web page, and there's also an NPM package for React. However, if you don't want to use the latter, and have a JavaScript React codebase, then this is a simple component wrapper (taken from this issue on GitHub) that you can use:

import {useEffect, useRef, useState} from "react";
import 'asciinema-player/dist/bundle/asciinema-player.css';

export default function AsciinemaPlayer({src, ...asciinemaOptions}) {
    const ref = useRef(null);
    const [player, setPlayer] = useState()

    useEffect(() => {
        import("asciinema-player").then(p => {
            setPlayer(p)
        })
    }, [])

    useEffect(() => {
        const currentRef = ref.current
        const instance = player?.create(src, currentRef, asciinemaOptions);
        return () => {
            instance?.dispose()
        }
    }, [src, player, asciinemaOptions]);

    return <div ref={ref}/>;
}

Use this component as follows, assuming the demo.cast file is accessible on /demo.cast:

<AsciinemaPlayer src="/demo.cast" loop/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment