Mount a 3D avatar in React
React can own the profile controls while Clayfaces owns the canvas. The important part is deciding which component owns the player when the user navigates away during a download.
Read the guideSeparate source modules from static geometry
In a React app with a JavaScript bundler, copy the downloaded Web directory beside the component below. Its relative import points to Web/character.js. Serve the matching WebAssets directory at /clayfaces/WebAssets/. If the app is deployed under a different path, change the assets URL to the directory your server actually exposes. Include the trailing slash.
Use this component in the client-rendered part of the app. The host div supplies the stage dimensions. A ref holds the player without rerendering React on every animation frame.
Give each effect its own stage
Each effect creates a child element for its own player. When cleanup runs, it detaches that element immediately. If initialization finishes later, the canceled effect disposes the player it just received. This also handles React Strict Mode’s extra setup and cleanup during development.
import { useEffect, useRef, useState } from 'react';
import { createClayfaces } from './Web/character.js';
export default function AvatarCard() {
const host = useRef(null);
const player = useRef(null);
const [ready, setReady] = useState(false);
const [message, setMessage] = useState('');
useEffect(() => {
const stage = document.createElement('div');
stage.style.cssText = 'width:100%;height:100%';
host.current.append(stage);
let removed = false;
let owned;
createClayfaces(stage, { assets: '/clayfaces/WebAssets/' })
.then(avatar => {
if (removed) return avatar.dispose();
owned = player.current = avatar;
setReady(true);
})
.catch(() => {
if (!removed) setMessage('The avatar could not load.');
});
return () => {
removed = true;
owned?.dispose();
player.current = null;
stage.remove();
};
}, []);
return <section>
<div ref={host} style={{ width: 'min(100%, 20rem)', aspectRatio: '1' }} />
<button disabled={!ready} onClick={() => player.current?.play('victory_hand')
.catch(() => setMessage('The gesture could not load.'))}>
Peace sign
</button>
<p role="status">{message}</p>
</section>;
}