### Install Dependencies and Start Dev Server
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Commands to install all project dependencies and start the development server for the monorepo.
```bash
pnpm install # Install dependencies
pnpm run dev # Start dev server (all packages)
```
--------------------------------
### Install @playcanvas/react and PlayCanvas
Source: https://github.com/playcanvas/react/blob/main/README.md
Install the necessary packages using npm. This command installs both the @playcanvas/react wrapper and the core PlayCanvas engine.
```bash
npm install @playcanvas/react playcanvas
```
--------------------------------
### Install @playcanvas/react in an existing project
Source: https://github.com/playcanvas/react/blob/main/packages/lib/README.md
Install the library using npm in your existing React project.
```bash
npm install @playcanvas/react
```
--------------------------------
### Install @playcanvas/blocks and playcanvas
Source: https://github.com/playcanvas/react/blob/main/packages/blocks/README.md
Install the necessary packages using npm. This is the first step to using the building blocks.
```bash
npm install @playcanvas/blocks playcanvas
```
--------------------------------
### Install PlayCanvas React (With Physics)
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Command to install @playcanvas/react along with the sync-ammo package for physics support.
```bash
npm install @playcanvas/react playcanvas react react-dom sync-ammo
```
--------------------------------
### Install PlayCanvas React (Basic)
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Command to install the core @playcanvas/react library and its essential dependencies without physics support.
```bash
npm install @playcanvas/react playcanvas react react-dom
```
--------------------------------
### Install Monorepo Dependencies
Source: https://github.com/playcanvas/react/blob/main/README.md
Installs all project dependencies for the monorepo using pnpm.
```bash
pnpm install
```
--------------------------------
### Install AI Rules for @playcanvas/react
Source: https://github.com/playcanvas/react/blob/main/packages/lib/README.md
Installs AI rules for @playcanvas/react by downloading a rules file to the .cursor/rules directory.
```bash
mkdir -p .cursor/rules && curl -s https://developer.playcanvas.com/user-manual/playcanvas-react/rules -o .cursor/rules/playcanvas-react.mdc
```
--------------------------------
### Install React 19.1.0+
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Command to install React and ReactDOM versions compatible with React 19.x for PlayCanvas React.
```bash
npm install react@19 react-dom@19
```
--------------------------------
### Install React 18.3.1+
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Command to install React and ReactDOM versions compatible with React 18.x for PlayCanvas React.
```bash
npm install react@18 react-dom@18
```
--------------------------------
### Environment Detection Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Demonstrates how to import and use the environment detection utility from @playcanvas/react/utils.
```typescript
import { env } from '@playcanvas/react/utils/env';
// env values: 'development', 'production', 'test'
```
--------------------------------
### Graphics Device Options Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/utilities.md
Demonstrates how to pass custom configuration options to the graphics device during application initialization using the `graphicsDeviceOptions` prop.
```typescript
```
--------------------------------
### Use Physics Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/hooks.md
Example component demonstrating how to use the `usePhysics` hook to display physics status or errors.
```typescript
function PhysicsDebug() {
const { isPhysicsLoaded, physicsError } = usePhysics();
if (physicsError) {
return
Physics Error: {physicsError.message}
;
}
return Physics Ready: {isPhysicsLoaded}
;
}
```
--------------------------------
### Use Material Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/hooks.md
Example of using the `useMaterial` hook to create a colored material for a sphere entity.
```typescript
function ColoredEntity() {
const material = useMaterial({
diffuse: [1, 0, 0],
emissive: [0.2, 0, 0]
});
return (
);
}
```
--------------------------------
### Basic Click Handling Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/pointer-events.md
Demonstrates how to attach an onClick handler to an Entity to toggle a state when the entity is clicked.
```typescript
function ClickableEntity() {
const [clicked, setClicked] = useState(false);
return (
setClicked(!clicked)}
>
);
}
```
--------------------------------
### Basic Application Setup
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/application.md
Demonstrates the fundamental usage of the Application component to render a scene with entities, a camera, and a renderable object. Ensure necessary components like Camera and Render are imported.
```typescript
import { Application, Entity } from '@playcanvas/react';
import { Camera, Render } from '@playcanvas/react/components';
export function Scene() {
return (
);
}
```
--------------------------------
### Spot Light Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Adds a spot light to an entity. Sets position, rotation, range, and type.
```typescript
// Spot light
```
--------------------------------
### Install PlayCanvas React Rules for Cursor
Source: https://github.com/playcanvas/react/blob/main/README.md
Installs the PlayCanvas React rules for the Cursor IDE. Ensure you have `mkdir` and `curl` commands available.
```bash
mkdir -p .cursor/rules && curl -s https://raw.githubusercontent.com/playcanvas/react/main/packages/lib/.playcanvas-react.mdc -o .cursor/rules/playcanvas-react.mdc
```
--------------------------------
### Default Canvas Setup with Application Component
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Demonstrates how the `` component automatically manages the creation and styling of the canvas element.
```typescript
{/* Scene content */}
```
--------------------------------
### Fetch Asset Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/utilities.md
Demonstrates how to use the `fetchAsset` function to load a 'container' type asset with progress reporting. Ensure `useApp` hook is available and the application instance is passed.
```typescript
import { fetchAsset } from '@playcanvas/react/utils';
import { useApp } from '@playcanvas/react/hooks';
function AssetLoader() {
const app = useApp();
const [asset, setAsset] = useState(null);
useEffect(() => {
fetchAsset({
app,
url: 'models/character.glb',
type: 'container',
onProgress: (meta) => {
console.log(`Loading: ${(meta.progress * 100).toFixed(0)}%`);
}
})
.then(setAsset)
.catch(console.error);
}, [app]);
return asset ? : ;
}
```
--------------------------------
### Install AI Rules for Blocks
Source: https://github.com/playcanvas/react/blob/main/packages/lib/README.md
Installs AI rules for PlayCanvas Blocks using npx, adding them to your project's registry and @playcanvas/react configuration.
```bash
npx shadcn@latest add https://developer.playcanvas.com/user-manual/playcanvas-react/r/blocks.json
```
--------------------------------
### Accessing Application and Assets with Hooks
Source: https://github.com/playcanvas/react/blob/main/_autodocs/INDEX.md
Shows how to use the `useApp` and `useAsset` hooks to get the application instance and load assets, including their loading state.
```typescript
const app = useApp();
const { asset, loading, error } = useAsset(url, type);
```
--------------------------------
### Import Utilities from @playcanvas/react/utils
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Example of importing utility functions like fetchAsset from the utils subpath.
```typescript
// Utilities
import { fetchAsset } from '@playcanvas/react/utils';
```
--------------------------------
### Pointer Event Lifecycle Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/pointer-events.md
Demonstrates the sequence of pointer events fired during a typical user interaction, including over, down, up, click, and out.
```typescript
function EventSequence() {
return (
console.log('Over')}
onPointerDown={() => console.log('Down')}
onPointerUp={() => console.log('Up')}
onClick={() => console.log('Click')}
onPointerOut={() => console.log('Out')}
>
);
}
// Output on user interaction:
// Over
// Down
// Up
// Click
// Out
```
--------------------------------
### Specifying Graphics Device Preference
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/application.md
Demonstrates how to set a preferred order for graphics device types using the `deviceTypes` prop. This example prioritizes WebGPU over WebGL2.
```typescript
import { DEVICETYPE_WEBGPU, DEVICETYPE_WEBGL2 } from 'playcanvas';
```
--------------------------------
### Modify.Component Usage Examples
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/gltf.md
Examples showing how to modify a render component's properties and how to remove a light component using Modify.Component.
```typescript
// Modify render component
// Remove a component
```
--------------------------------
### Import Main Exports from @playcanvas/react
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Example of importing core components like Application, Entity, and Container from the main entry point of the @playcanvas/react library.
```typescript
// Main exports
import { Application, Entity, Container } from '@playcanvas/react';
```
--------------------------------
### Entity Component Usage
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/entity.md
Demonstrates how to use the Entity component with various properties and child components, including basic setup, nested entities, pointer events, and transform manipulation.
```APIDOC
## Entity Component
### Description
The `Entity` component is the fundamental building block of a PlayCanvas scene. It represents a node in the scene hierarchy and can have components (Camera, Render, Light, etc.) and child entities attached to it. Entities are the containers for all interactive 3D objects in your scene.
### Component Signature
```typescript
export const Entity = forwardRef(function Entity(props, ref): React.ReactElement | null)
```
### EntityProps
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| name | string | No | "Untitled" | The name of the entity in the scene hierarchy |
| position | [number, number, number] | No | [0, 0, 0] | Local position relative to parent entity as [x, y, z] |
| scale | [number, number, number] | No | [1, 1, 1] | Local scale relative to parent entity as [x, y, z] |
| rotation | [number, number, number] | No | [0, 0, 0] | Local rotation in euler angles (degrees) as [x, y, z] |
| onPointerDown | (event: SyntheticPointerEvent) => void | No | undefined | Callback fired when pointer is pressed over this entity |
| onPointerUp | (event: SyntheticPointerEvent) => void | No | undefined | Callback fired when pointer is released over this entity |
| onPointerOver | (event: SyntheticPointerEvent) => void | No | undefined | Callback fired when pointer moves over this entity |
| onPointerOut | (event: SyntheticPointerEvent) => void | No | undefined | Callback fired when pointer leaves this entity |
| onClick | (event: SyntheticMouseEvent) => void | No | undefined | Callback fired on click (pointer down + up) over this entity |
| children | React.ReactNode | No | undefined | Child entities and components |
### Return Type
Returns a React element that provides the entity context to child components via `ParentContext`.
### Ref Type
The component forwards a reference to the internal PlayCanvas `Entity` instance, allowing direct access to the underlying entity API.
```typescript
const entityRef = useRef(null);
useEffect(() => {
if (entityRef.current) {
console.log(entityRef.current.getWorldPosition());
}
}, []);
```
### Behavior
- **Scene Hierarchy:** Each entity is automatically added as a child to its parent entity when mounted
- **Cleanup:** Entity is removed from parent and destroyed when component unmounts
- **Pointer Events:** When pointer event handlers are provided, the entity is registered with the pointer events system
- **Property Updates:** Position, scale, and rotation updates are applied to the entity without re-mounting
- **Context:** Becomes the parent context for all child components
### Examples
#### Basic Entity with Render Component
```typescript
```
#### Nested Entities
```typescript
```
#### With Pointer Events
```typescript
console.log('pressed')}
onClick={() => console.log('clicked')}>
```
#### Using Ref to Access Underlying Entity
```typescript
const cubeRef = useRef(null);
function CubeWithAnimation() {
useEffect(() => {
const entity = cubeRef.current;
if (!entity) return;
const animate = () => {
const pos = entity.getLocalPosition();
entity.setLocalPosition(pos.x, pos.y + 0.01, pos.z);
requestAnimationFrame(animate);
};
animate();
}, []);
return (
);
}
```
#### With Rotation and Scale
```typescript
```
### Event Callbacks
#### SyntheticPointerEvent
Pointer events (onPointerDown, onPointerUp, onPointerOver, onPointerOut) receive a `SyntheticPointerEvent`:
```typescript
interface SyntheticPointerEvent {
entity: pc.Entity;
screenX: number;
screenY: number;
// ... additional pointer properties
}
```
#### SyntheticMouseEvent
The onClick callback receives a `SyntheticMouseEvent`:
```typescript
interface SyntheticMouseEvent {
entity: pc.Entity;
screenX: number;
screenY: number;
// ... additional mouse properties
}
```
### Notes
- Positions, scales, and rotations are always relative to the parent entity
- Euler angle rotations are specified in degrees (not radians)
- Entity names are for debugging and referencing within the scene hierarchy
- Pointer events require the entity to have a render component to be raycast-pickable
- All coordinates follow PlayCanvas conventions (right-handed coordinate system)
```
--------------------------------
### OrbitControls Usage Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/scripts.md
Demonstrates how to use the OrbitControls component to configure camera orbit navigation with specific distance limits and mouse sensitivity.
```typescript
import { OrbitControls } from '@playcanvas/react/scripts';
```
--------------------------------
### Point Light Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Adds an omnidirectional (point) light to an entity. Configures position, range, and type.
```typescript
// Point light
```
--------------------------------
### Import Component Library from @playcanvas/react/components
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Example of importing specific components like Camera, Render, and Light from the components subpath.
```typescript
// Component library
import { Camera, Render, Light } from '@playcanvas/react/components';
```
--------------------------------
### Hover Effects Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/pointer-events.md
Shows how to use onPointerOver and onPointerOut handlers to change an entity's scale when the pointer hovers over it.
```typescript
function HoverableEntity() {
const [isHovered, setIsHovered] = useState(false);
return (
setIsHovered(true)}
onPointerOut={() => setIsHovered(false)}
>
);
}
```
--------------------------------
### Import Scripts from @playcanvas/react/scripts
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Example of importing pre-built scripts such as OrbitControls and AutoRotator from the scripts subpath.
```typescript
// Scripts
import { OrbitControls, AutoRotator } from '@playcanvas/react/scripts';
```
--------------------------------
### Import Hooks from @playcanvas/react/hooks
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Example of importing React hooks like useApp, useAsset, and useAppEvent from the hooks subpath.
```typescript
// Hooks
import { useApp, useAsset, useAppEvent } from '@playcanvas/react/hooks';
```
--------------------------------
### Color Representation Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/utilities.md
Illustrates how PlayCanvas React handles color values using arrays for RGBA or RGB, and hex strings. This example shows setting light and material colors.
```typescript
```
--------------------------------
### Loading Models with State Management
Source: https://github.com/playcanvas/react/blob/main/_autodocs/INDEX.md
Provides an example of loading a model using `useModel` and handling the loading, error, and success states to conditionally render content.
```typescript
const { asset, loading, error } = useModel('model.glb');
if (loading) return ;
if (error) return ;
if (asset) return ;
```
--------------------------------
### Modify.Node Examples
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/gltf.md
Demonstrates various ways to use the Modify.Node component with different path syntaxes for selecting and modifying nodes, including removing children.
```typescript
// Remove lights from the entire hierarchy
// Modify specific named entity
// Clear children from nodes matching a pattern
{/* This removes all descendants */}
```
--------------------------------
### Manual Context Access Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/contexts.md
Shows how to access a context directly using React's `useContext` hook, although using custom hooks is generally preferred.
```typescript
import { AppContext } from '@playcanvas/react/hooks';
import { useContext } from 'react';
function LowLevelAccess() {
const app = useContext(AppContext);
if (!app) {
throw new Error('Must be used inside ');
}
return null;
}
```
--------------------------------
### Directional Light Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Adds a directional light to an entity, simulating sunlight. Adjusts intensity and rotation.
```typescript
// Directional light (sun)
```
--------------------------------
### Nested Entities Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/entity.md
Illustrates creating a parent entity with two child entities, each containing a different render component.
```typescript
```
--------------------------------
### RigidBody Component Usage Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Attaches a dynamic rigid body to a sphere entity for physics simulation. Sets mass and uses the Render component.
```typescript
```
--------------------------------
### Custom Canvas Setup
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Use this snippet when you need to manage the canvas element externally. It allows passing a ref to the canvas for custom styling or integration.
```typescript
const canvasRef = useRef(null);
return (
<>
{/* Scene content */}
>
);
```
--------------------------------
### Camera Component Usage Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Renders a Camera component within an Entity. Adjusts field of view, near, and far clipping planes.
```typescript
```
--------------------------------
### Complex Interaction Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/pointer-events.md
Illustrates handling multiple pointer events (down, up, click) on a single entity to manage its interaction state and log event details.
```typescript
function InteractiveObject() {
const [state, setState] = useState('idle');
const handlePointerDown = (event) => {
console.log('Pressed at:', event.screenX, event.screenY);
setState('pressed');
};
const handlePointerUp = () => {
setState('idle');
};
const handleClick = (event) => {
console.log('Clicked entity:', event.entity.name);
// Perform action
};
return (
);
}
```
--------------------------------
### Access Entity with useEntity Hook
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/gltf.md
Use the useEntity hook to get a reference to a specific entity within a GLTF hierarchy by its path. The entity can then be manipulated, for example, by setting its local rotation.
```typescript
function ModelController() {
const headEntity = useEntity('head');
const characterBody = useEntity('character');
useEffect(() => {
if (headEntity) {
headEntity.setLocalEulerAngles(0, 45, 0);
}
}, [headEntity]);
return null;
}
```
--------------------------------
### Create a new @playcanvas/react project
Source: https://github.com/playcanvas/react/blob/main/packages/lib/README.md
Use this command to quickly set up a new project with the @playcanvas/react template.
```bash
npx create playcanvas@latest -t react-t
```
--------------------------------
### Use Parent Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/hooks.md
Example component that uses `useParent` to access and log the name of its parent entity.
```typescript
function ChildComponent() {
const parent = useParent();
useEffect(() => {
console.log('Parent entity:', parent.name);
}, [parent]);
return null;
}
```
--------------------------------
### Setting up Physics Simulation
Source: https://github.com/playcanvas/react/blob/main/_autodocs/README.md
Enables physics simulation for the application and sets up a dynamic rigid body with a sphere collision shape. Requires the `usePhysics` context to be enabled.
```typescript
```
--------------------------------
### AutoRotator Usage Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/scripts.md
Example of using the AutoRotator component to rotate a sphere entity at a specified speed and axis.
```typescript
import { AutoRotator } from '@playcanvas/react/scripts';
```
--------------------------------
### Clone PlayCanvas React Starter Template
Source: https://github.com/playcanvas/react/blob/main/README.md
Clone the official starter template repository to quickly set up a new project with PlayCanvas and React.
```bash
git clone https://github.com/marklundin/playcanvas-react-template.git
```
--------------------------------
### Physics Simulation
Source: https://github.com/playcanvas/react/blob/main/_autodocs/README.md
Demonstrates setting up a physics simulation by enabling physics on the `Application` and adding physics components like `RigidBody` and `Collision` to entities.
```APIDOC
## Physics Simulation
### Description
This example shows how to enable and utilize the physics engine within PlayCanvas React. It demonstrates adding a dynamic rigid body to an entity and defining its collision shape.
### Components and Features
- `Application usePhysics`: Enables the physics simulation for the entire application.
- `Entity`: A game object in the scene that can have physics properties.
- `RigidBody`: Component that defines the physical properties of an entity (e.g., dynamic, static, kinematic).
- `Collision`: Component that defines the shape used for physics collision detection.
- `Render`: Component to visually represent the entity.
### Code Example
```typescript
```
```
--------------------------------
### Gltf Component Usage Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/gltf.md
Example demonstrating how to use the Gltf component with Modify children to selectively alter nodes and components within a GLTF model.
```typescript
const { asset } = useModel('model.glb');
return (
);
```
--------------------------------
### Context Error Handling Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/contexts.md
Demonstrates the error thrown when a context hook is used outside of its required provider component. For example, useApp must be used within an Application component.
```typescript
// ❌ This throws an error - used outside
const app = useApp(); // Error: useApp must be used within an Application component
// ✅ This works - used inside
{/* useApp works here */}
```
--------------------------------
### useParent
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Get parent Entity. Retrieves the parent entity in the PlayCanvas scene graph.
```APIDOC
## useParent
### Description
Get parent Entity.
### Method
`useParent()`
### Returns
- `Entity`: The parent Entity.
```
--------------------------------
### Configuring Scene Environment
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Shows how to set up global scene lighting, skybox, and atmospheric effects using the Environment component. Requires loading skybox and environment atlas assets.
```typescript
const { asset: skybox } = useAsset('skybox.jpg', 'texture');
const { asset: envAtlas } = useEnvAtlas('env.jpg');
```
--------------------------------
### Main Entry Point Exports
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Directly usable components and hooks from the main @playcanvas/react entry point.
```APIDOC
## Components
### Application
- **Type**: React.FC
- **File**: Application.tsx
- **Description**: Root component creating canvas and PlayCanvas app
### ApplicationWithoutCanvas
- **Type**: React.FC
- **File**: Application.tsx
- **Description**: App root without automatic canvas creation
### Container
- **Type**: React.FC
- **File**: Container.tsx
- **Description**: Renders GLB/GLTF container assets
### Entity
- **Type**: React.FC
- **File**: Entity.tsx
- **Description**: Scene hierarchy building block
### Gltf
- **Type**: React.FC
- **File**: gltf/components/Gltf.tsx
- **Description**: GLTF scene loader with modification support
### Modify
- **Type**: Namespace
- **File**: gltf/components/Modify.tsx
- **Description**: Container for modification rules (Modify.Node, etc.)
## Hooks
### useEntity
- **Type**: (path: string | PathPredicate) => Entity | null
- **File**: gltf/hooks/use-entity.ts
- **Description**: Access entities in GLTF hierarchy by path
```
--------------------------------
### Build PlayCanvas React Libraries
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Commands to build the @playcanvas/react and @playcanvas/blocks packages individually.
```bash
pnpm run build:lib # Build @playcanvas/react
pnpm run build:blocks # Build @playcanvas/blocks
```
--------------------------------
### Basic Entity with Render Component
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/entity.md
Demonstrates creating a basic entity with a name and position, and attaching a render component to display a box.
```typescript
```
--------------------------------
### Rendering a Scene
Source: https://github.com/playcanvas/react/blob/main/_autodocs/README.md
Demonstrates how to set up a basic 3D scene using PlayCanvas React components like Application, Entity, Camera, and Light.
```APIDOC
## Rendering a Scene
### Description
This example shows how to render a basic 3D scene. It includes setting up the main application, defining entities with positions, adding a camera with a field of view, and including a directional light.
### Components Used
- `Application`: The root component for a PlayCanvas React application.
- `Entity`: Represents a node in the scene graph, used for positioning and hierarchy.
- `Camera`: Defines the viewpoint for rendering the scene.
- `Light`: Adds lighting to the scene, here a directional light is used.
### Code Example
```typescript
import { Application, Entity } from '@playcanvas/react';
import { Camera, Render, Light } from '@playcanvas/react/components';
export function Scene() {
return (
);
}
```
```
--------------------------------
### Using a Custom Script
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/scripts.md
Demonstrates how to attach and configure a custom 'Bouncer' script to an entity.
```typescript
import Bouncer from './bouncer';
```
--------------------------------
### Entity with Rotation and Scale Properties
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/entity.md
Example of setting an entity's rotation and scale properties. Note that rotations are in Euler degrees.
```typescript
```
--------------------------------
### useApp
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Get PlayCanvas Application instance. Provides access to the main PlayCanvas application object within your React component tree.
```APIDOC
## useApp
### Description
Get PlayCanvas Application instance.
### Method
`useApp()`
### Returns
- `Application`: The PlayCanvas Application instance.
```
--------------------------------
### Run All Tests
Source: https://github.com/playcanvas/react/blob/main/packages/lib/test/README.md
Execute all tests in the project using npm test.
```bash
npm test
```
--------------------------------
### env
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/utilities.md
Detects the build environment. Available values are 'test', 'production', or development (default).
```APIDOC
## env
### Description
Detects the build environment. Available values are 'test', 'production', or development (default).
### Method
`env` (string)
### Example
```typescript
import { env } from '@playcanvas/react/utils/env';
if (env === 'development') {
console.log('Debug info');
}
```
```
--------------------------------
### Resolved GLTF Rule Type
Source: https://github.com/playcanvas/react/blob/main/_autodocs/types.md
Represents a GLTF rule after conflict resolution and specificity ordering, including entity GUID and component actions.
```typescript
interface MergedRule {
entityGuid: string;
clearChildren: boolean;
componentActions: Map;
addChildren: ReactNode[];
}
```
--------------------------------
### Loading a Model
Source: https://github.com/playcanvas/react/blob/main/_autodocs/README.md
Illustrates how to load a 3D model (e.g., GLB/GLTF) using the `useModel` hook and display it using the `Container` component.
```APIDOC
## Loading a Model
### Description
This example demonstrates how to load a 3D model file using the `useModel` hook and render it within the scene using the `Container` component. It also includes basic loading and error state handling.
### Hooks and Components Used
- `useModel`: A React hook to asynchronously load a model asset.
- `Container`: A component that renders a loaded model asset.
### Code Example
```typescript
import { useModel } from '@playcanvas/react/hooks';
import { Container } from '@playcanvas/react';
function ModelViewer() {
const { asset, loading, error } = useModel('model.glb');
if (loading) return Loading...
;
if (error) return Error: {error}
;
return ;
}
```
```
--------------------------------
### Components Entry Point Exports
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Directly usable components from the @playcanvas/react/components entry point.
```APIDOC
## Component Exports
### Camera
- **Type**: React.FC
- **File**: components/Camera.tsx
- **Description**: Camera component for viewing
### GSplat
- **Type**: React.FC
- **File**: components/GSplat.tsx
- **Description**: Gaussian splat rendering
### Light
- **Type**: React.FC
- **File**: components/Light.tsx
- **Description**: Light source (directional, omni, spot)
### Render
- **Type**: React.FC
- **File**: components/Render.tsx
- **Description**: 3D geometry rendering (primitives or assets)
### Script
- **Type**: React.FC
- **File**: components/Script.tsx
- **Description**: Custom script attachment
### Sprite
- **Type**: React.FC
- **File**: components/Sprite.tsx
- **Description**: 2D sprite rendering
### Align
- **Type**: React.FC
- **File**: components/Align.tsx
- **Description**: UI element alignment
### Anim
- **Type**: React.FC
- **File**: components/Anim.tsx
- **Description**: Animation playback control
### RigidBody
- **Type**: React.FC
- **File**: components/RigidBody.tsx
- **Description**: Physics rigid body simulation
### Collision
- **Type**: React.FC
- **File**: components/Collision.tsx
- **Description**: Collision shape definition
### Screen
- **Type**: React.FC
- **File**: components/Screen.tsx
- **Description**: UI screen space
### Element
- **Type**: React.FC
- **File**: components/Element.tsx
- **Description**: UI element within screen
### Gizmo
- **Type**: React.FC
- **File**: components/Gizmo.tsx
- **Description**: Transform gizmo visualization
### Environment
- **Type**: React.FC
- **File**: components/Environment.tsx
- **Description**: Global scene lighting and skybox
```
--------------------------------
### Import GLTF Modifications from @playcanvas/react
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Example of importing GLTF-related components and hooks like Gltf, Modify, and useEntity, which are re-exported from the main entry point.
```typescript
// GLTF modifications (re-exported from main)
import { Gltf, Modify, useEntity } from '@playcanvas/react';
```
--------------------------------
### Main Package Package.json
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Configuration for the main @playcanvas/react package, defining its name, version, module type, and export paths.
```json
{
"name": "@playcanvas/react",
"version": "0.11.4",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./components": "./dist/components/index.js",
"./scripts": "./dist/scripts/index.js",
"./utils": "./dist/utils/index.js",
"./hooks": "./dist/hooks/index.js"
}
}
```
--------------------------------
### Modify.Node with Custom Path Predicate
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/gltf.md
Example of using a custom path predicate function with Modify.Node for advanced entity filtering based on specific criteria.
```typescript
entity.name.startsWith('Bone')}>
```
--------------------------------
### Pointer Interaction
Source: https://github.com/playcanvas/react/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt
Documentation for handling pointer events, including click detection and raycasting.
```APIDOC
## Pointer Interaction Documentation
### Description
Details how to implement pointer interactions, such as click detection on 3D objects and raycasting for precise targeting.
### Usage
Guides developers on setting up event listeners for mouse and touch input to interact with the 3D scene.
### Key Areas Covered:
- Click detection on entities
- Raycasting for object selection
- Event flow and propagation
```
--------------------------------
### Utilities
Source: https://github.com/playcanvas/react/blob/main/_autodocs/INDEX.md
Utility functions for asset loading and other helper tasks.
```APIDOC
## Utilities (@playcanvas/react/utils)
- **fetchAsset** — Low-level asset loading
- **FetchAssetOptions** — Asset loading configuration
```
--------------------------------
### Environment Component
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Sets global scene lighting, skybox, and atmospheric effects.
```APIDOC
## Environment Component
### Description
Configures global lighting, skybox, and atmospheric properties for the scene.
### Props
- **type** ('skytype_dome' | 'skytype_infinite') - Optional - The type of sky to render.
- **showSkybox** (boolean) - Optional - Whether to display the skybox.
- **skybox** (Asset) - Optional - The skybox texture asset.
- **envAtlas** (Asset) - Optional - The environment atlas asset for reflections and lighting.
- Accepts additional environment properties.
```
--------------------------------
### Component Hierarchy Example
Source: https://github.com/playcanvas/react/blob/main/_autodocs/README.md
Illustrates the nested structure of PlayCanvas components within a React application. This hierarchy defines how entities, cameras, lights, and scripts are organized in the scene.
```jsx
(Scene root)
(Nested)
```
--------------------------------
### Load Asset with useAsset Hook
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Load assets into the application's registry using the `useAsset` hook. This hook takes a URL and type, returning the asset, loading status, and any errors.
```typescript
const { asset, loading, error } = useAsset(url, type);
```
--------------------------------
### Using ApplicationWithoutCanvas with a Custom Canvas
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/application.md
Illustrates how to use `ApplicationWithoutCanvas` when you manage the canvas element externally. A `useRef` hook is used to get a reference to the canvas, which is then passed to the component.
```typescript
export function CustomCanvasApp() {
const canvasRef = useRef(null);
return (
<>
>
);
}
```
--------------------------------
### Rendering Gaussian Splats
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/components.md
Demonstrates how to use the GSplat component to render Gaussian splat data, a modern technique for point cloud rendering. Requires fetching the asset first.
```typescript
const { asset } = useSplat('splats/scene.ply');
```
--------------------------------
### Build PlayCanvas React Library
Source: https://github.com/playcanvas/react/blob/main/README.md
Builds the main React library package within the monorepo.
```bash
pnpm run build:lib
```
--------------------------------
### Adding Interaction
Source: https://github.com/playcanvas/react/blob/main/_autodocs/README.md
Shows how to add click event listeners to entities to create interactive elements in the 3D scene, demonstrated by scaling an entity on click.
```APIDOC
## Adding Interaction
### Description
This example shows how to make entities interactive by attaching event listeners, specifically `onClick`. When an entity is clicked, its scale changes, providing visual feedback.
### Components and Event Handling
- `Entity`: Can receive event listeners like `onClick`.
- `onClick`: A prop on `Entity` that accepts a callback function to be executed when the entity is clicked.
### Code Example
```typescript
const [clicked, setClicked] = useState(false);
setClicked(!clicked)}
scale={clicked ? [1.2, 1.2, 1.2] : [1, 1, 1]}
>
```
```
--------------------------------
### Access PlayCanvas Application Instance
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/hooks.md
Use the `useApp` hook to get the current PlayCanvas Application instance within a React component. Ensure it's used inside an `` component.
```typescript
import { useApp } from '@playcanvas/react/hooks';
function MyComponent() {
const app = useApp();
useEffect(() => {
console.log('App root entity:', app.root);
console.log('Scene:', app.scene);
}, [app]);
return null;
}
```
--------------------------------
### Main Entry Point Exports
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Exports for core components and hooks from the main '@playcanvas/react' entry point.
```typescript
export { Application, ApplicationWithoutCanvas } from './Application.tsx';
export { Container } from './Container.tsx';
export { Entity } from './Entity.tsx';
export { Gltf } from './gltf/components/Gltf.tsx';
export { Modify } from './gltf/components/Modify.tsx';
```
```typescript
export { useEntity } from './gltf/hooks/use-entity.ts';
```
```typescript
export type {
GltfProps,
Rule,
Action,
MergedRule,
ModifyNodeProps,
ModifyLightProps,
ModifyRenderProps,
ModifyCameraProps,
PathPredicate,
EntityMetadata
} from './gltf/index.ts';
```
--------------------------------
### Enabling Physics in Application
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/application.md
Shows how to enable the PlayCanvas physics system by setting the `usePhysics` prop to true. This requires the 'sync-ammo' peer dependency.
```typescript
```
--------------------------------
### Accessing Underlying PlayCanvas Entity via Ref
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/entity.md
Demonstrates using `useRef` to get a reference to the internal PlayCanvas `Entity` instance. This allows direct manipulation of the entity's properties and methods, such as animating its position.
```typescript
const cubeRef = useRef(null);
function CubeWithAnimation() {
useEffect(() => {
const entity = cubeRef.current;
if (!entity) return;
const animate = () => {
const pos = entity.getLocalPosition();
entity.setLocalPosition(pos.x, pos.y + 0.01, pos.z);
requestAnimationFrame(animate);
};
animate();
}, []);
return (
);
}
```
--------------------------------
### Run Project Tests
Source: https://github.com/playcanvas/react/blob/main/README.md
Executes all tests for the monorepo packages.
```bash
pnpm test
```
--------------------------------
### Run PlayCanvas React Tests
Source: https://github.com/playcanvas/react/blob/main/_autodocs/configuration.md
Commands to execute tests, run tests in watch mode, and generate a test coverage report.
```bash
pnpm test # Run all tests
pnpm run test:watch # Watch mode
pnpm run test:coverage # Coverage report
```
--------------------------------
### Render a Sphere with PlayCanvas React
Source: https://github.com/playcanvas/react/blob/main/README.md
Demonstrates how to render a basic sphere in a React component using @playcanvas/react. It includes setting up the application, camera, and the renderable entity.
```jsx
import { Application, Entity } from '@playcanvas/react';
import { Camera, Render } from '@playcanvas/react/components';
import { OrbitControls } from '@playcanvas/react/scripts';
export function AssetViewer() {
return (
);
}
```
--------------------------------
### Run Tests with Coverage
Source: https://github.com/playcanvas/react/blob/main/packages/lib/test/README.md
Execute all tests and generate a code coverage report. This helps in identifying areas of the codebase that are not adequately tested.
```bash
npm test -- --coverage
```
--------------------------------
### useEnvAtlas
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Load environment atlas. Hook for loading environment atlas assets.
```APIDOC
## useEnvAtlas
### Description
Load environment atlas.
### Method
`useEnvAtlas(src, props)`
### Parameters
- `src` (string) - The source URL or path of the environment atlas asset.
- `props` (object) - Optional properties for asset loading.
### Returns
- `AssetResult`: An object containing the loaded asset and its status.
```
--------------------------------
### Type System
Source: https://github.com/playcanvas/react/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt
Documentation on the full TypeScript support, including type definitions and interfaces.
```APIDOC
## Type System Documentation
### Description
Details the comprehensive TypeScript support, including all type definitions, interfaces, and utility types used within the library.
### Usage
Helps developers leverage TypeScript for enhanced code quality, autocompletion, and compile-time error checking.
### Key Areas Covered:
- Core type definitions
- Interface expansions
- Type safety in API usage
```
--------------------------------
### Build PlayCanvas Blocks Components
Source: https://github.com/playcanvas/react/blob/main/README.md
Builds the high-level React components package for 3D use cases.
```bash
pnpm run build:blocks
```
--------------------------------
### useSplat
Source: https://github.com/playcanvas/react/blob/main/_autodocs/exports.md
Load splat asset. Hook specifically for loading splat assets.
```APIDOC
## useSplat
### Description
Load splat asset.
### Method
`useSplat(src, props)`
### Parameters
- `src` (string) - The source URL or path of the splat asset.
- `props` (object) - Optional properties for asset loading.
### Returns
- `AssetResult`: An object containing the loaded asset and its status.
```
--------------------------------
### Import @playcanvas/blocks CSS
Source: https://github.com/playcanvas/react/blob/main/packages/blocks/README.md
Import the necessary CSS for @playcanvas/blocks and specify the source path. This should be added to your main CSS file.
```css
@import "@playcanvas/blocks";
@source "../../node_modules/@playcanvas/blocks";
```
--------------------------------
### useModel
Source: https://github.com/playcanvas/react/blob/main/_autodocs/api-reference/hooks.md
Convenience hook for loading 3D model assets (GLB/GLTF). Equivalent to useAsset(src, 'container', props).
```APIDOC
## useModel
### Description
A convenience hook for loading 3D model assets (GLB/GLTF). This is equivalent to calling `useAsset(src, 'container', props)`.
### Signature
```typescript
export function useModel(
src: string,
props?: Record
): AssetResult
```
### Parameters
#### Query Parameters
- **src** (string) - Required - Asset URL
- **props** (Record) - Optional - Additional loader options.
### Return Type
See `AssetResult` from `useAsset` documentation.
### Example
```typescript
const { asset, loading } = useModel('assets/statue.glb');
if (loading) return ;
return (
);
```
```