# React

Use RupaPlayer, useRupaPlayer and usePlayerState with React 18 or 19, and the element or mountFile on React 16 and 17.

## Quick start

1. Install the player. `@rupamotion/player/react` needs React 18 or later (an optional peer dependency).

   ```sh
   npm i @rupamotion/player
   ```

2. Put `hero.rupaplay` (export as **Player file** in Rupamotion) in `public/`.

3. Render the component. `markup="auto"` writes the file's markup into the empty `div`:

   ```tsx
   import { RupaPlayer } from "@rupamotion/player/react";

   export function Hero() {
   	return <RupaPlayer src="/hero.rupaplay" markup="auto" />;
   }
   ```

That's it: the animation plays.

## Need control?

Give `<RupaPlayer>` a `ref` and read its state with `usePlayerState`. See [Control playback](/guides/control/) for what a
player can do and [Events](/guides/events/) for what it tells you.

```tsx
import { useRef } from "react";
import { RupaPlayer, usePlayerState } from "@rupamotion/player/react";
import type { Player } from "@rupamotion/player";

// The children are your server-rendered markup (markup="keep", the default).
export function Hero() {
	const player = useRef<Player>(null); // the player once the file is mounted, null before
	const { paused } = usePlayerState(player); // rendered again at each state change, play and pause
	return (
		<>
			<RupaPlayer ref={player} src="/hero.rupaplay" className="hero" onError={console.warn}>
				<h1 className="hero-title">Your heading</h1>
			</RupaPlayer>
			<button onClick={() => (paused ? player.current?.play() : player.current?.pause())}>
				{paused ? "Play" : "Pause"}
			</button>
		</>
	);
}
```

The `ref` of `<RupaPlayer>` is the `Player` (its `div` is `player.root`). `usePlayerState` takes that ref or a player and
gives `{ player, state, paused }`. The module is `"use client"`. React 18 or later is an optional peer dependency, and
only `/react` needs it.

## The snippet in JSX

For the full snippet, put its markup in JSX and mount it with the table the export wrote as `<base>.player.json`:

```tsx
import { useRef } from "react";
import { useRupaPlayer, usePlayerState } from "@rupamotion/player/react";
import data from "./hero.player.json";

export function Snippet() {
	const ref = useRef<HTMLDivElement>(null);
	const player = useRupaPlayer<"enter" | "hover">(ref, data); // null until mounted
	const { state } = usePlayerState(player);
	return (
		<>
			<div ref={ref} className="hero" data-rupa="">
				{/* the markup of the snippet, its classes as exported */}
			</div>
			<p>{state}</p>
			<button onClick={() => player?.setSpeed(2)}>Faster</button>
		</>
	);
}
```

## React 16.8 and 17

`@rupamotion/player/react` needs React 18 or later. On React 16.8 or 17, use the `<rupa-player>` element or `mountFile`
in an effect.

### The element

Import `@rupamotion/player/element` once. React 16 and 17 set the attributes of a custom element as strings and do not
wire `on...` props for custom events, so the listeners go through a ref. `rupaready` carries the player in
`event.detail.player`; `rupaerror` carries the error in `event.detail.error`.

```tsx
import "@rupamotion/player/element";
import { useEffect, useRef, useState } from "react";
import type { Player } from "@rupamotion/player";
import type { FileError } from "@rupamotion/player/file";

// For TypeScript, declare the element in JSX.IntrinsicElements["rupa-player"].
export function Hero() {
	const ref = useRef<HTMLElement>(null);
	const [player, setPlayer] = useState<Player | null>(null);

	useEffect(() => {
		const el = ref.current;
		if (!el) return;
		const onReady = (event: Event) => setPlayer((event as CustomEvent<{ player: Player }>).detail.player);
		const onError = (event: Event) => console.warn((event as CustomEvent<{ error: FileError }>).detail.error);
		el.addEventListener("rupaready", onReady);
		el.addEventListener("rupaerror", onError);
		return () => {
			el.removeEventListener("rupaready", onReady);
			el.removeEventListener("rupaerror", onError);
		};
	}, []);

	return (
		<>
			<rupa-player ref={ref} src="/hero.rupaplay" cloak="" />
			<button onClick={() => player?.play("hover")}>Hover</button>
		</>
	);
}
```

The element destroys its player when React removes it.

### mountFile in an effect

`mountFile` resolves `{ player }` or `{ error }` and never rejects. A hook of your own keeps a `cancelled` flag for a
result that arrives after the component is gone, and destroys the player in the cleanup. `on` returns the function that
removes the listener.

```tsx
import { useEffect, useRef, useState } from "react";
import type { RefObject } from "react";
import { mountFile } from "@rupamotion/player/file";
import type { FileError } from "@rupamotion/player/file";
import type { Player } from "@rupamotion/player";

export function useRupaFile(ref: RefObject<HTMLElement>, src: string) {
	const [player, setPlayer] = useState<Player | null>(null);
	const [error, setError] = useState<FileError | null>(null);
	const [state, setState] = useState<string | null>(null);
	const [paused, setPaused] = useState(false);

	useEffect(() => {
		const root = ref.current;
		if (!root) return;
		setPlayer(null); // a new src: the player of the last file is gone
		setError(null);
		let cancelled = false;
		let mounted: Player | null = null;
		let unsubscribe: Array<() => void> = [];
		mountFile(root, src, { markup: "keep" }).then((result) => {
			if (result.error) {
				if (!cancelled) setError(result.error);
				return;
			}
			const next = result.player;
			if (cancelled) return next.destroy(); // the component went away while the file loaded
			mounted = next;
			const sync = () => {
				setState(next.state);
				setPaused(next.paused);
			};
			unsubscribe = (["statechange", "play", "pause"] as const).map((type) => next.on(type, sync));
			sync();
			setPlayer(next);
		});
		return () => {
			cancelled = true;
			unsubscribe.forEach((off) => off());
			mounted?.destroy(); // no state update here: React 16 warns about one after an unmount
		};
	}, [ref, src]);

	return { player, error, state, paused };
}

export function Hero() {
	const ref = useRef<HTMLDivElement>(null);
	const { player, state, paused } = useRupaFile(ref, "/hero.rupaplay");
	return (
		<>
			<div ref={ref}>
				<h1 className="hero-title">Your heading</h1>
			</div>
			<p>{state}</p>
			<button onClick={() => (paused ? player?.play() : player?.pause())}>{paused ? "Play" : "Pause"}</button>
		</>
	);
}
```

For your own markup and a table you already hold, call `mount(root, data)` from `@rupamotion/player` in the same place.
