Skip to content

@pawnjs/react ​

React bindings: a component that owns an engine, a component that draws a view into page layout, and hooks for systems and entities. Read world state in UI with koota's own koota/react hooks (useQuery, useTrait, ...).

The core does not need React; this package is optional. It needs React 19.

<Pawn> ​

Creates an engine on its own canvas, keeps it sized to the container, starts it, and provides it (and its koota world) to children. The engine is disposed on unmount.

tsx
import { 
Position
,
Rotation
,
Visual
} from "@pawnjs/core";
import {
Pawn
,
useSpawn
,
useSystem
} from "@pawnjs/react";
import {
useQuery
} from "koota/react";
function
App
() {
return ( <
Pawn
style
={{
position
: "fixed",
inset
: 0 }}>
<
Spinner
/>
<
Count
/>
</
Pawn
>
); }
PropMeaning
configEngine options such as lights and background (all but canvas, renderer, camera and fit); read once, on mount.
cameraCamera of the default full-canvas view, or camera options for one; read once. Defaults to a perspective camera at (0, 2, 6) looking at the origin. Pass null to start without views.
onCreatedCalled for each engine <Pawn> creates, once it is running. Install plugins here. React's StrictMode mounts twice in development, so it gets two engines, and the first one is disposed right after.
className, styleFor the container <div>.
canvasStyleExtra style for the canvas; when given, the canvas's own box decides its size.
childrenRendered once the engine exists.

To draw only when something changes, pass a DemandDriver in config (driver: new DemandDriver()). Traits your UI sets (through koota's hooks or entity.set) are seen as long as they move or restyle what is drawn.

Without WebGL (a GPU turned off, a remote desktop) <Pawn> throws WebGLUnavailableError when it mounts; an error boundary around it shows a page without 3D instead. Pass onContextLost and onContextRestored in config for a context lost later.

Plugins that load asynchronously (physics) can be installed from onCreated. The engine may be disposed by the time they load (an unmount, or StrictMode's first mount), and engine.use throws on a disposed engine, so check first:

tsx
<
Pawn
onCreated
={async (
engine
) => {
const
physics
= await
createPhysics
();
if (!
engine
.
disposed
)
engine
.
use
(
physics
);
}} />

<EntityLabel> ​

Renders its children in an element pinned to an entity on screen, through the core Labels plugin (installed on first use). Use it inside <Pawn>; the element sits over the canvas in <Pawn>'s container.

tsx
function 
NodeTag
({
entity
,
name
}: {
entity
:
Entity
;
name
: string }) {
return ( <
EntityLabel
entity
={
entity
}
offset
={{
y
: 2 }}>
<
button
type
="button"
onClick
={() =>
select
(
entity
)}>
{
name
}
</
button
>
</
EntityLabel
>
); }
PropMeaning
entityEntity to follow; nothing is shown while it is undefined.
offset, align, viewAs for the Label trait.
className, styleFor the label element; the plugin owns its position, transform and visibility.

Hooks ​

useEngine() ​

Returns the engine of the closest <Pawn>. Throws outside of one.

useSystem(system, options?) ​

Runs a system while the component is mounted. The latest system is always called, so it may close over props and state. options takes phase and order, as in engine.addSystem().

tsx
function 
Spinner
() {
useSystem
(({
world
,
elapsed
}) => {
world
.
query
(
Orbit
,
Position
).
updateEach
(([
orbit
,
p
]) => {
p
.
x
=
Math
.
cos
(
elapsed
*
orbit
.
speed
) *
orbit
.
radius
;
p
.
z
=
Math
.
sin
(
elapsed
*
orbit
.
speed
) *
orbit
.
radius
;
}); }); return null; }

useSpawn(factory, deps) ​

Spawns an entity while the component is mounted and destroys it on unmount or when deps change. factory returns what engine.spawn takes: traits, or a prefab (or its registered name) with overrides, such as () => [Tower, { position: { x: 2 } }]. Returns the entity, or undefined before the first effect.

tsx
function 
Orbiter
({
radius
}: {
radius
: number }) {
useSpawn
(
() => [
Position
,
Rotation
,
Orbit
({
radius
,
speed
: 1 }),
Visual
(new
Mesh
(
geometry
,
material
))],
[
radius
],
); return null; }

useEntityEvent(entity, type, listener) ​

Listens to an entity event while the component is mounted, also for events bubbling up from the entity's children. The latest listener is called, so it may use props and state. entity may be undefined, such as the result of useSpawn before its first effect; nothing is listened to then.

tsx
function 
Crate
() {
const [
clicks
,
setClicks
] =
useState
(0);
const
crate
=
useSpawn
(() => [
Shape
({
kind
: "box" }),
Clickable
], []);
useEntityEvent
(
crate
, "click", () =>
setClicks
((
n
) =>
n
+ 1));
return <
p
>Clicked {
clicks
} times</
p
>;
}

useAssetProgress() ​

Returns { loaded, total } for the glTF files loading now, from the AssetProgress world trait that the engine's Assets plugin keeps; without the plugin it returns { loaded: 0, total: 0 }. Re-renders as files finish.

tsx
function 
LoadingBar
() {
const {
loaded
,
total
} =
useAssetProgress
();
return
loaded
<
total
? <
progress
value
={
loaded
}
max
={
total
} /> : null;
}

Reading the world in UI ​

<Pawn> wraps children in koota's WorldProvider, so koota/react hooks work directly:

tsx
function 
Count
() {
const
orbiters
=
useQuery
(
Orbit
);
return <
span
>{
orbiters
.
length
} entities</
span
>;
}

Views in page layout ​

<PawnView> is a <div> the engine draws a view into. The view follows the element's box as the page lays out and scrolls. Put the <Pawn> canvas over the whole page and start it without a default view:

tsx
import { 
Pawn
,
PawnView
} from "@pawnjs/react";
<
Pawn
camera
={null}
config
={{
enableTransparency
: true }}
style
={{
overflow
: "visible" }}
canvasStyle
={{
position
: "fixed",
inset
: 0,
width
: "100vw",
height
: "100vh",
pointerEvents
: "none",
}} > <
main
className
="grid">
{
cards
.
map
((
card
) => (
<
PawnView
key
={
card
.
id
}
camera
={
card
.
camera
}
className
="aspect-square">
<
h2
>{
card
.
title
}</
h2
>
</
PawnView
>
))} </
main
>
</
Pawn
>
PropMeaning
cameraCamera drawn into this element's box. A new camera creates a new view.
backgroundClear color of the view; null (default) keeps what is underneath.
name, className, stylePassed to the view and the <div>.
childrenPage content laid over the view.

Because the canvas lets pointer events through, install Input with element: document.body to pick through the views. The Views example puts it all together.