@ringozz/react-godot
v4.7.2-614
Published
A React renderer for Godot Engine via @ringozz/godot
Readme
@ringozz/react-godot
Declarative, component-driven Godot 4 scene graph management in React. Built for high-performance applications using @ringozz/godot.
Overview
@ringozz/react-godot brings a React Three Fiber (R3F)-like developer experience to Godot. It provides a custom React reconciler that renders React components directly into Godot's live engine scene tree (SceneTree).
If you are familiar with React Three Fiber, the core paradigms will feel instantly recognizable:
- Declarative Nodes: Godot 3D/2D nodes (e.g.,
<RigidBody3D>,<Camera3D>,<DirectionalLight3D>) map directly to JSX components. - Resource Attachment: Use the
attachprop to assign nested Godot resources (materials, shapes, meshes, environments) directly to parent properties. - Reactive Engine Loop: Use hooks like
useSignalto hook into Godot signals (processFrame,windowInput) without triggering React state re-renders.
Installation & Setup
1. Dependencies
npm install @ringozz/react-godot react2. TypeScript Configuration (tsconfig.json)
To enable custom JSX element resolution for Godot nodes, configure jsxImportSource and module settings in tsconfig.json:
{
"compilerOptions": {
"module": "esnext",
"target": "es2025",
"jsx": "react-jsx",
"jsxImportSource": "@ringozz/react-godot",
"rewriteRelativeImportExtensions": true,
"verbatimModuleSyntax": true
}
}Application Entry & Portal Rendering
1. Mounting with createRoot(parent: Node)
createRoot is the primary entry point for mounting a React component tree into a Godot target Node (typically SceneTree.root).
import { Engine } from '@ringozz/godot/Engine';
import { SceneTree } from '@ringozz/godot/SceneTree';
import { createRoot } from '@ringozz/react-godot';
import { App } from './App';
const tree = Engine.getMainLoop() as SceneTree;
const { render } = createRoot(tree.root);
render(<App />);- Returns
{ render, unmount }. - Enables React
StrictModeautomatically in development (NODE_ENV === 'development').
2. Render Portals with createPortal(children, container)
createPortal allows rendering a React sub-tree into a different Godot Node in the hierarchy—such as a CanvasLayer for 2D UI overlays, a SubViewport, or an isolated container node.
import { createPortal } from '@ringozz/react-godot';
import { Label } from '@ringozz/godot/Label';
function Overlay({ overlayNode }: { overlayNode: Node }) {
return createPortal(
<Label text="HUD Overlay" position={[20, 20]} />,
overlayNode
);
}- Container Constraint: The target
containermust be a GodotNode(it cannot targetResourceinstances). - Cleanup: Unmounting the portal safely disposes of and frees its child Godot nodes.
Core Concepts & Patterns
1. Existing Objects with object Prop
If you already have a pre-existing Godot Node, Resource, or PackedScene instance (e.g. instantiated from C++ or loaded from disk), pass it via the object prop to adopt it into the React component tree instead of letting the reconciler instantiate a new object:
<Node object={myExistingGodotNode}>
{/* Children attached to existing node */}
</Node>objectis immutable on a mounted instance. It selects the host instance once, at creation. A re-render that changesobjecton an existing element throws (Cannot change the \object` of a mounted instance) because React cannot swap a fiber's Godot node — remount with a newkey` instead.- A
PackedSceneobjectis instantiated once per host mount — each element gets a fresh node tree; the result is a plainNode(not.reference()'d) freed on unmount. The samePackedScenecan feed multiple elements; give same-type siblings stablekeys. - Dynamic same-type sibling lists need stable
keys. Godot host nodes are identity, not content: React reconciles keyless siblings by position, so deleting the first of two same-type siblings reuses its Godot node for the survivor. A plain state re-render does this too, and Bun's web dev server makes it especially likely — its React Fast Refresh re-renders the edited component in place (no app re-run), reusing the same fibers and Godot nodes, so a deleted sibling's node can survive on its neighbor and the neighbor's node is freed. Addkey="..."to each dynamically toggled same-type sibling to keep nodes pinned to the right elements.
1b. Attaching a Script with script
Use the script prop to attach a Script resource (e.g. an imported GDScript .gd module) to a node on creation. The script is attached before the node enters the tree, so Godot fires _ready and auto-enables the script's _process/_input — no manual set_process(true)/set_process_input(true) calls needed:
import controller from './camera_controller.gd';
<Camera3D script={use(controller)} current={true} fov={55} />- Attach before tree entry means
_ready/_process/_inputwork. Attaching to an already-in-tree node (e.g. in auseEffect) never fires_readyand leaves_process/_inputdisabled — preferscriptover an effect for scripted nodes. scriptis immutable on a mounted instance. A re-render that changesscripton an existing element throws — remount with a newkeyto swap the compiled script.
2. Resource Nesting with attach
In Godot, nodes often hold references to Resource objects (such as shapes, meshes, materials, or environments). Use the attach prop to automatically assign a child resource to a specific property on its parent:
/* Attaching a shape to CollisionShape3D */
<CollisionShape3D>
<BoxShape3D attach="shape" size={[1, 1, 1]} />
</CollisionShape3D>
/* Attaching a material override to MeshInstance3D */
<MeshInstance3D>
<BoxMesh attach="mesh" />
<StandardMaterial3D attach="materialOverride" albedoColor={[1, 0, 0]} />
</MeshInstance3D>
/* Attaching physics material to RigidBody3D */
<RigidBody3D>
<PhysicsMaterial attach="physicsMaterialOverride" bounce={0.8} />
</RigidBody3D>
/* Attaching environment to WorldEnvironment */
<WorldEnvironment>
<Environment attach="environment" backgroundColor={[0.1, 0.1, 0.2]} />
</WorldEnvironment>Note for physics bodies: attach="shape" goes on the shape resource element (e.g. <BoxShape3D attach="shape" />), never on the CollisionShape3D node itself — Node.add_child requires a Node, and shapes are Resources, so an attach on CollisionShape3D adds the shape as a child node and fails. Likewise, mesh children of a physics body must be wrapped in a MeshInstance3D (a RigidBody3D/StaticBody3D has no mesh/materialOverride props to attach to).
3. Properties & Helper Types
Props map directly to Godot node setters and properties. Helper arrays are automatically cast to Godot types:
- Vectors / value types: value types are named tuples — flat (
Vector3,Color,Rect2, …) are scalar-labeled tuples (Vector3 = [x, y, z],Color = [r, g, b, a?]); nested (AABB/Transform2D/Basis/Transform3D/Projection) are row-labeled tuples of the flat element alias (Transform3D = [x, y, z, origin], each row aVector3), soposition={[0, 1, 0]},transform={[[1, 0, 0], [0, 1, 0], [0, 0, 1], [10, 20, 30]]}. Getters return the same labeled shape (node.positionis[x, y, z]); direct setters accept them too (node.position = [1, 2, 3]). Wrong-arity arrays fail typecheck (position={[1, 2]}errors) — exceptColor's trailinga, which is optional ([r, g, b, a?], alpha defaults 1; it's the only value type with a partial scalar ctor). The math API lives as named functions per type module —import * as v3 from '@ringozz/godot/Vector3', thenv3.normalized(v),v3.dot(a, b); construction usesfromXxxfactories (basis.fromAxisAngle(axis, angle),transform3d.fromBasisOrigin(basis, origin)). - Colors:
albedoColor={[1, 0.2, 0.2]}(aColoris just[r, g, b, a?]). - Packed arrays:
Packed*Array-typed props (e.g.Gradient.colors/offsets) accept plain JS arrays — elements convert with the array's element type, socolors={[[0.5, 0, 0, 1], [1, 1, 1, 1]]}works;new PackedVector2Array([[1, 2], [3, 4]])works too. The same element-aware conversion applies to direct setters and method args:gradient.colors = [[1, 0, 0, 1], [0, 1, 0, 1]],addPoint(0.5, [1, 0, 0, 1]), andPhysicsRayQueryParameters3D.create([1, 2, 3], [4, 5, 6])all accept tuples. - Array-typed props (
GodotArray, e.g.CodeEdit.lineLengthGuidelines,Font.fallbacks) accept plain JS arrays directly — they become a GodotArray. - Sub-properties / Dash props: Set individual vector/color components directly using dash syntax:
<BoxMesh attach="mesh" size-x={0.5} size-y={1.0} size-z={0.5} />
Text content: text nodes are unsupported, but string/number children — and arrays of all-string/all-number children — are flattened into the node's text prop, so <Label>Hello</Label> works. Mixed children (containing elements) throw; use an explicit text prop instead, and never pass string children to a node without a text prop.
4. Engine Signals & Event Subscription (useSignal)
Subscribe to Godot engine signals cleanly with useSignal.
import { Engine } from '@ringozz/godot';
import { SceneTree } from '@ringozz/godot/SceneTree';
import { useSignal } from '@ringozz/react-godot';
const tree = Engine.getMainLoop() as SceneTree;
const root = tree.root;
// Subscribe to frame updates (process loop)
useSignal(tree.processFrame, () => {
// Update animations, camera matrix, physics targets, etc.
});
// Subscribe to window input events
useSignal(root.windowInput, (event) => {
if (event instanceof InputEventMouseMotion) {
// Handle mouse motion
}
});Signal JSX props (pressed, toggled, valueChanged, textSubmitted, ...) are typed as the signal's callback — pass a plain function, no cast needed:
<Button text="Play" pressed={() => start()} />
<CheckButton text="Debug" toggled={(on) => setDebug(on)} />
<HSlider value={round} valueChanged={(v) => setRound(v)} />Signal handlers are connected before value props are applied within a commit (Instance.assign), so the handler a render installs is already current when a value setter fires its signal (e.g. Range.value emits value_changed). Note that programmatic value sets still emit (Godot semantics) — if you feed a slider's value back from your own state, guard the handler (e.g. compare against the live store) or the emission loops back into your reducer.
ComponentProps only exposes writable members: read-only props (e.g. Node.multiplayer) and methods are not settable props.
Full Example
Below is a complete interactive 3D physics scene with custom camera controls and physics bodies:
import { Engine, Key, MouseButton } from '@ringozz/godot';
import type { Color } from '@ringozz/godot';
import { BoxMesh } from '@ringozz/godot/BoxMesh';
import { BoxShape3D } from '@ringozz/godot/BoxShape3D';
import { Camera3D } from '@ringozz/godot/Camera3D';
import { CollisionShape3D } from '@ringozz/godot/CollisionShape3D';
import { DirectionalLight3D } from '@ringozz/godot/DirectionalLight3D';
import { BGMode, Environment, ToneMapper } from '@ringozz/godot/Environment';
import { InputEventMouseButton } from '@ringozz/godot/InputEventMouseButton';
import { InputEventMouseMotion } from '@ringozz/godot/InputEventMouseMotion';
import { MeshInstance3D } from '@ringozz/godot/MeshInstance3D';
import { PhysicsMaterial } from '@ringozz/godot/PhysicsMaterial';
import { RigidBody3D } from '@ringozz/godot/RigidBody3D';
import { SceneTree } from '@ringozz/godot/SceneTree';
import { SphereMesh } from '@ringozz/godot/SphereMesh';
import { SphereShape3D } from '@ringozz/godot/SphereShape3D';
import { StandardMaterial3D } from '@ringozz/godot/StandardMaterial3D';
import { StaticBody3D } from '@ringozz/godot/StaticBody3D';
import { WorldEnvironment } from '@ringozz/godot/WorldEnvironment';
import { useSignal, type ComponentProps } from '@ringozz/react-godot';
import { useRef, type ReactElement } from 'react';
const tree = Engine.getMainLoop() as SceneTree;
const root = tree.root;
function PhysBody({ color, shape, children, ...rest }: {
color: Color;
shape: ReactElement;
} & ComponentProps<typeof RigidBody3D>) {
return (
<RigidBody3D {...rest}>
<MeshInstance3D>
{children}
<StandardMaterial3D attach="materialOverride" albedoColor={color} />
</MeshInstance3D>
<CollisionShape3D>{shape}</CollisionShape3D>
</RigidBody3D>
);
}
export function App() {
const cameraRef = useRef<Camera3D>(null);
const isDragging = useRef(false);
const yaw = useRef(0.7);
const pitch = useRef(0.3);
const zoom = useRef(7);
useSignal(root.windowInput, (event) => {
if (event instanceof InputEventMouseMotion && isDragging.current) {
yaw.current -= event.relative[0] * 0.005;
pitch.current = Math.max(-1.4, Math.min(1.4, pitch.current + event.relative[1] * 0.005));
} else if (event instanceof InputEventMouseButton) {
if (event.buttonIndex === MouseButton.MOUSE_BUTTON_LEFT) {
isDragging.current = event.pressed;
}
}
event.free();
});
useSignal(tree.processFrame, () => {
const camera = cameraRef.current;
if (!camera) return;
const cx = zoom.current * Math.cos(pitch.current) * Math.sin(yaw.current);
const cy = zoom.current * Math.sin(pitch.current) + 1;
const cz = zoom.current * Math.cos(pitch.current) * Math.cos(yaw.current);
camera.position = [cx, cy, cz];
camera.lookAt([0, 1, 0], [0, 1, 0]);
});
return (
<>
<WorldEnvironment>
<Environment attach="environment" tonemapMode={ToneMapper.TONE_MAPPER_AGX} backgroundMode={BGMode.BG_COLOR} backgroundColor={[0.05, 0.1, 0.25]} />
</WorldEnvironment>
<DirectionalLight3D name="Sun" rotation={[-0.8, 0.5, 0]} />
<Camera3D name="Camera" ref={cameraRef} />
{/* Physics Sphere */}
<PhysBody name="BouncySphere" position={[0, 4, 0]} color={[0.2, 1, 0.2]}
shape={<SphereShape3D attach="shape" radius={0.5} />}>
<SphereMesh attach="mesh" radius={0.5} height={1} />
<PhysicsMaterial attach="physicsMaterialOverride" bounce={0.8} />
</PhysBody>
{/* Ground Plane */}
<StaticBody3D name="Ground">
<CollisionShape3D>
<BoxShape3D attach="shape" size={[10, 0.1, 10]} />
</CollisionShape3D>
<MeshInstance3D>
<BoxMesh attach="mesh" size-x={10} size-y={0.1} size-z={10} />
<StandardMaterial3D attach="materialOverride" albedoColor={[0.2, 0.2, 0.25]} />
</MeshInstance3D>
</StaticBody3D>
</>
);
}API Summary
| Export | Type | Description |
| :--- | :--- | :--- |
| createRoot(parent) | Function | Mounts a React component tree into a target Godot Node (e.g. tree.root). Returns { render, unmount }. |
| createPortal(children, container) | Function | Renders children into a target Godot Node (e.g. CanvasLayer or SubViewport). |
| useSignal(signal, callback) | Hook | Connects a callback to a Godot object signal (e.g. tree.processFrame, node.treeEntered). Disconnects on unmount. |
| useMutableCallback(fn) | Hook | Returns a RefObject whose .current always points to the latest callback implementation. |
| useTween<NodeT>(create, deps) | Hook | Reactive tween-as-prop-value. Returns [spring, tweenRef] — spread spring onto a node; tweenRef.current is the live native Tween. The optional node type (useTween<Node3D>) types to/from array goals as that node's value-type tuples. |
| ComponentProps<T> | Type | Utility type to infer valid React JSX props for any Godot node class T. |
Animating props with useTween
useTween animates a node's properties declaratively. You describe the target values once per to key; spreading the returned spring onto a node binds the tween to it. Re-rendering with the same deps keeps the same tween (nothing restarts); changing deps creates a new Tween and animates from the current values.
const [spring, tweenRef] = useTween<Node3D>(() => ({
from: { position: [0, 0, 0] },
to: { position: [0, 2, 0], globalRotation: [0, 90, 0] },
config: { duration: 0.6, transition: TransitionType.TRANS_QUAD, ease: EaseType.EASE_IN_OUT },
delay: 0, loops: 1, immediate: false,
onFinished: () => {},
}), [x, z]);
return <Node3D {...spring} />;springholds one function pertokey (spread them all onto the node; each contributes its own prop's tweener to the sharedTween). Array values are converted to the property's value type.- Node-typed goals: call
useTween<Node3D>(...)soto/fromare typed against that node's props —position: [0, 2, 0]and nestedbasis: [[…]]infer asVector3/Basis, with noas Vector3casts. Only scalar-number and value-type props are tweenable (signals,Noderefs, bools, strings, containers are rejected); the returnedspringis that whole prop set (all optional), so{...spring}stays JSX-spreadable. A bareuseTween(...)keeps array goals loose (number[]). tweenRef.currentis the live native GodotTween, created when the node mounts (null before that):tweenRef.current?.kill(),?.pause(),?.play(),?.setSpeedScale(n),?.isRunning(),?.finished…configmaps to the Godot Tween API:duration(seconds),transition/ease(TransitionType/EaseType— the tween's defaults),easing(a[0,1]→[0,1]function →setCustomInterpolator),speedScale.onStartfires when the tween is created/bound (on mount or whendepschange), before it starts stepping.onFinishedfires on natural completion only (Godot'sfinishedsignal);kill()/unmount don't fire it, so no stale callbacks.- Unwrapping: replacing a springed prop with a plain value (e.g. dropping
{...spring}forposition={[9, 0, 0]}) does not stop the running tween — it keeps animating to its target and the tween's value wins over the plain value. Stop it withtweenRef.current?.kill().
