### Basic Usage of Example Component
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/example.mdx
Demonstrates how to instantiate the Example component with a required font path. This component is primarily used for testing and contribution purposes.
```tsx
```
--------------------------------
### Imperative API via Ref
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/example.mdx
Shows how to access the Example component's imperative API using a React ref. The API provides methods to increment or decrement the internal counter state.
```tsx
const api = useRef()
```
```tsx
type ExampleApi = {
incr: (x?: number) => void
decr: (x?: number) => void
}
```
--------------------------------
### Install Drei Package using npm
Source: https://github.com/pmndrs/drei/blob/master/docs/getting-started/introduction.mdx
This command installs the @react-three/drei package, which provides essential helpers and abstractions for @react-three/fiber. Ensure you have Node.js and npm installed.
```bash
npm install @react-three/drei
```
--------------------------------
### Install and Import @react-three/drei
Source: https://context7.com/pmndrs/drei/llms.txt
Instructions for installing the library via npm and importing components for both web and React Native environments.
```bash
npm install @react-three/drei
```
```jsx
// Web usage
import { PerspectiveCamera, OrbitControls, Environment } from '@react-three/drei'
// React Native usage
import { PerspectiveCamera, OrbitControls } from '@react-three/drei/native'
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/pmndrs/drei/blob/master/README.md
Installs all project dependencies listed in the package.json file using Yarn. This is a standard step after setting up the Node.js and Yarn environment.
```shell
yarn install
```
--------------------------------
### Example Component Properties
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/example.mdx
Defines the TypeScript interface for the Example component props, including optional color, debug, and bevelSize settings.
```tsx
type ExampleProps = {
font: string
color?: Color
debug?: boolean
bevelSize?: number
}
```
--------------------------------
### Basic Usage of Clone
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/clone.mdx
Examples showing how to clone a single object or an array of objects from a loaded GLTF model.
```jsx
const { nodes } = useGLTF(url)
return (
)
```
```jsx
```
--------------------------------
### Implement AccumulativeShadows Component
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/accumulative-shadows.mdx
Basic implementation example showing how to wrap RandomizedLight components within an AccumulativeShadows container to generate soft shadows.
```jsx
```
--------------------------------
### Center Component Usage Examples
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/center.mdx
Demonstrates basic usage of the Center component and an advanced implementation using onCentered to scale a model to the viewport height.
```jsx
```
```jsx
function ScaledModel() {
const viewport = useThree((state) => state.viewport)
return (
container.scale.setScalar(viewport.height / height)}>
)
}
```
--------------------------------
### Install Node.js using NVM
Source: https://github.com/pmndrs/drei/blob/master/README.md
Installs and uses a specific Node.js version managed by NVM. It also provides an option to set the installed version as the default. Ensure the Node.js version satisfies the project's requirements.
```shell
nvm install
nvm use
node -v # make sure your version satisfies package.json#engines.node
nvm alias default node
```
--------------------------------
### Basic Stage Setup with Contact Shadows - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/stage.mdx
Demonstrates a basic implementation of the Stage component using default settings and 'contact' shadows. This is suitable for general scene setup where simple ground shadows are desired.
```jsx
```
--------------------------------
### Resize Component Usage
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/resize.mdx
Demonstrates how to wrap 3D elements with the Resize component to enforce scaling constraints. Examples show default behavior and axis-specific constraints.
```jsx
```
```jsx
```
--------------------------------
### Install and Activate Yarn using Corepack
Source: https://github.com/pmndrs/drei/blob/master/README.md
Enables Corepack to manage Node.js package managers and activates Yarn based on the 'packageManager' field in package.json. Verifies the installed Yarn version meets project specifications.
```shell
corepack enable
corepack prepare --activate
yarn -v # make sure your version satisfies package.json#engines.yarn
```
--------------------------------
### Example Usage of View Component in JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/portals/view.mdx
Demonstrates how to integrate the View component within a React application. It shows nesting HTML content alongside View components and rendering them within a Canvas using View.Port. This example highlights the flexibility of positioning and styling different views.
```jsx
return (
Html content here
)
```
--------------------------------
### RenderCubeTexture Usage Example
Source: https://github.com/pmndrs/drei/blob/master/docs/portals/render-cube-texture.mdx
Demonstrates how to implement RenderCubeTexture within a React Three Fiber scene. It shows attaching the component to a material's envMap property using a ref.
```jsx
const api = useRef(null!)
// ...
```
--------------------------------
### Gradual Quality Adjustment Example
Source: https://github.com/pmndrs/drei/blob/master/docs/performances/performance-monitor.mdx
Shows how to use the `onChange` callback for gradual quality adjustments. The `factor` prop controls the initial state, and the `setDpr` function uses this factor to calculate a smoothed dpr value.
```jsx
const [dpr, setDpr] = useState(2)
return (
setDpr(Math.floor(0.5 + 1.5 * factor, 1))} />
```
--------------------------------
### Implement MotionPathControls with curves
Source: https://github.com/pmndrs/drei/blob/master/docs/controls/motion-path-controls.mdx
Examples showing how to define paths using both declarative JSX components and imperative Three.js curve instances.
```jsx
```
```jsx
```
--------------------------------
### DragControls Usage Examples
Source: https://github.com/pmndrs/drei/blob/master/docs/gizmos/drag-controls.mdx
Demonstrates basic implementation of DragControls as a wrapper and advanced usage as a controlled component by disabling autoTransform.
```jsx
```
```jsx
const matrix = new THREE.Matrix4()
return (
matrix.copy(localMatrix)}
/>
)
```
--------------------------------
### Run Local Visual Tests with Playwright
Source: https://github.com/pmndrs/drei/blob/master/README.md
Installs Playwright browser binaries and then executes the project's test suite, including visual regression tests. Assumes the project has been built.
```shell
npx playwright install
yarn build
yarn test
```
--------------------------------
### Basic useAnimations with GLTF - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/use-animations.mdx
Demonstrates the basic usage of the useAnimations hook with a GLTF model. It extracts nodes, materials, animations, and then sets up the animation mixer, actions, and clips. An example of playing the 'jump' animation is included. Dependencies: useGLTF, useAnimations.
```jsx
const { nodes, materials, animations } = useGLTF(url)
const { ref, mixer, names, actions, clips } = useAnimations(animations)
useEffect(() => {
actions?.jump.play()
})
return (
```
--------------------------------
### Fallback Mechanism Example
Source: https://github.com/pmndrs/drei/blob/master/docs/performances/performance-monitor.mdx
Illustrates setting a `flipflops` limit to trigger an `onFallback` callback. This is useful for defining a lowest possible baseline when performance remains unstable after multiple adjustments.
```jsx
setDpr(1)} />
```
--------------------------------
### Implement CubeCamera Render Prop
Source: https://github.com/pmndrs/drei/blob/master/docs/cameras/cube-camera.mdx
An example demonstrating how to use the CubeCamera component to apply a generated reflection texture to a material within a React Three Fiber scene.
```jsx
{(texture) => (
)}
```
--------------------------------
### Basic ContactShadows Setup (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/contact-shadows.mdx
This snippet demonstrates the basic usage of the ContactShadows component with common properties like opacity, scale, blur, far, resolution, and color. It's a React JSX implementation.
```jsx
```
--------------------------------
### Run Tests in Docker for CI Consistency
Source: https://github.com/pmndrs/drei/blob/master/README.md
Executes the full installation, build, and test process within a Docker container. This ensures the tests run in an environment identical to the CI, using a pre-built Playwright Docker image. Snapshots are system-dependent.
```shell
docker run --init --rm \
-v $(pwd):/app -w /app \
ghcr.io/pmndrs/playwright:drei \
sh -c "corepack enable && yarn install && yarn build && yarn test"
```
--------------------------------
### Monitor loading progress with useProgress
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/progress-use-progress.mdx
This example demonstrates how to use the useProgress hook within a Suspense fallback component to display the current loading percentage of Three.js assets. It accesses properties like active, progress, and errors to provide real-time feedback to the user.
```jsx
function Loader() {
const { active, progress, errors, item, loaded, total } = useProgress()
return {progress} % loaded
}
return (
}>
)
```
--------------------------------
### Basic Video Texture Usage - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/video-texture-use-video-texture.mdx
A simple example demonstrating how to use the `useVideoTexture` hook to apply a video as a texture to a mesh. It assumes the video file is available at '/video.mp4'.
```jsx
const texture = useVideoTexture("/video.mp4")
return (
```
--------------------------------
### MediaStream Video Texture - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/video-texture-use-video-texture.mdx
This example shows how to use `useVideoTexture` with a `MediaStream`, such as one obtained from `getDisplayMedia`. It utilizes `React.Suspense` to handle the asynchronous loading of the stream.
```jsx
const [stream, setStream] = useState(null)
return (
setStream(await navigator.mediaDevices.getDisplayMedia({ video: true }))}>
}>
```
```jsx
function VideoMaterial({ src }) {
const texture = useVideoTexture(src)
return
}
```
--------------------------------
### Using useBounds Hook for Camera Control
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/bounds.mdx
Illustrates how to utilize the `useBounds` hook within a component to interact with the Bounds context. It shows examples of refreshing bounds, fitting the camera, clipping near/far planes, moving the camera, and changing its orientation based on specific conditions or object references.
```jsx
function Foo() {
const bounds = useBounds()
useEffect(() => {
// Calculate scene bounds
bounds.refresh().clip().fit()
// Or, focus a specific object or box3
// bounds.refresh(ref.current).clip().fit()
// bounds.refresh(new THREE.Box3()).clip().fit()
// Or, move the camera to a specific position, and change its orientation
// bounds.moveTo([0, 10, 10]).lookAt({ target: [5, 5, 0], up: [0, -1, 0] })
// For orthographic cameras, reset has to be used to center the view (fit would only change its zoom to match the bounding box)
// bounds.refresh().reset().clip().fit()
}, [...])
}
```
--------------------------------
### ScrollControls Usage Example
Source: https://github.com/pmndrs/drei/blob/master/docs/controls/scroll-controls.mdx
Demonstrates how to implement ScrollControls in a React application. It shows the nesting of `` components for both canvas and HTML content, and how to utilize the `useScroll` hook within a component to react to scroll events.
```jsx
{/* Canvas contents in here will *not* scroll, but receive useScroll! */}
{/* Canvas contents in here will scroll along */}
{/* DOM contents in here will scroll along */}
html in here (optional)
second page
third page
```
--------------------------------
### Using Outlines Component (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/outlines.mdx
Demonstrates how to use the Outlines component within a React Three Fiber scene. It shows a basic setup with a mesh, a box geometry, a material, and the Outlines component applied with custom thickness and color.
```jsx
```
--------------------------------
### Get Face Mesh World Direction - TypeScript
Source: https://github.com/pmndrs/drei/blob/master/docs/shapes/facemesh.mdx
Example of using the `meshRef` from the Facemesh API to get the world direction of the face mesh. This is useful for orienting other objects relative to the face.
```typescript
api.meshRef.current.localToWorld(new THREE.Vector3(0, 0, -1))
```
--------------------------------
### Render 3D Text with Text3D Component (React/JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/text3d.mdx
Demonstrates how to render 3D text using the Text3D component. It requires a font URL and accepts various options for TextGeometry. Any ThreeJS material can be applied. The example shows basic usage with a meshNormalMaterial.
```jsx
Hello world!
```
--------------------------------
### Implement KeyboardControls Provider
Source: https://github.com/pmndrs/drei/blob/master/docs/controls/keyboard-controls.mdx
Shows how to wrap an application with the KeyboardControls provider and define a mapping of keys to specific actions.
```tsx
enum Controls {
forward = 'forward',
back = 'back',
left = 'left',
right = 'right',
jump = 'jump',
}
function App() {
const map = useMemo[]>(()=>[
{ name: Controls.forward, keys: ['ArrowUp', 'KeyW'] },
{ name: Controls.back, keys: ['ArrowDown', 'KeyS'] },
{ name: Controls.left, keys: ['ArrowLeft', 'KeyA'] },
{ name: Controls.right, keys: ['ArrowRight', 'KeyD'] },
{ name: Controls.jump, keys: ['Space'] },
], [])
return (
```
--------------------------------
### Prefetch Draco Binaries
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/gltf-use-gltf.mdx
Optimizes loading performance by adding prefetch link tags to the HTML head for Draco decoder files.
--------------------------------
### Radial Gradient Texture Example - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/gradient-texture.mdx
This example illustrates the creation of a radial gradient texture. It imports necessary components and enums from './GradientTexture'. It showcases advanced options like 'width', 'type', 'innerCircleRadius', and 'outerCircleRadius' for customizing the radial gradient.
```jsx
import { GradientTexture, GradientType } from './GradientTexture'
```
--------------------------------
### Linear Gradient Texture Example - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/gradient-texture.mdx
This example demonstrates how to create a basic linear gradient texture using the GradientTexture component in JSX. It shows how to define color stops and corresponding colors for the gradient. The 'size' property is optional and defaults to 1024.
```jsx
```
--------------------------------
### Implement Basic SpotLight
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/spot-light.mdx
A basic implementation of the SpotLight component. It accepts props such as distance, angle, attenuation, and anglePower to control the light's appearance.
```jsx
```
--------------------------------
### Configure Scene Lighting with Environment
Source: https://context7.com/pmndrs/drei/llms.txt
Sets up global environment maps for lighting and background rendering. Supports presets, custom HDR files, ground projection, and dynamic content rendering within the environment.
```jsx
import { Canvas } from '@react-three/fiber'
import { Environment, Float } from '@react-three/drei'
import * as THREE from 'three'
function Scene() {
return (
)
}
```
--------------------------------
### PerspectiveCamera Rendering to RenderTarget (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/cameras/perspective-camera.mdx
Provides an example of using PerspectiveCamera to render content into a RenderTarget, utilizing a render function that receives the texture.
```jsx
{(texture) => (
)}
```
--------------------------------
### Imperative Mesh Sampling using Refs
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/sampler.mdx
Shows how to use the Sampler component when declarative composition is not possible. By passing mesh and instances via refs, you can sample from loaded GLTF models.
```tsx
const { nodes } = useGLTF('my/mesh/url')
const mesh = useRef(nodes)
const instances = useRef()
return <>
>
```
--------------------------------
### OrthographicCamera for RenderTarget
Source: https://github.com/pmndrs/drei/blob/master/docs/cameras/orthographic-camera.mdx
This example shows how to use OrthographicCamera to render contents into a RenderTarget. The camera's output (texture) can then be used as a material map for other objects, such as a plane.
```jsx
{(texture) => (
)}
```
--------------------------------
### Implement Select Component Usage
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/select.mdx
Demonstrates how to wrap 3D objects with the Select component and retrieve the current selection state using the useSelect hook.
```jsx
items}>
function Foo() {
const selected = useSelect()
```
--------------------------------
### GizmoHelper Component Usage (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/gizmos/gizmo-helper.mdx
Demonstrates how to use the GizmoHelper component to visualize and control camera position. It accepts props for alignment, margins, update callbacks, and render priority. Child components like GizmoViewport or GizmoViewcube can be used to render the actual gizmo.
```jsx
{/* alternative: */}
```
--------------------------------
### Basic OrthographicCamera Setup
Source: https://github.com/pmndrs/drei/blob/master/docs/cameras/orthographic-camera.mdx
This snippet demonstrates the basic usage of the OrthographicCamera component. It sets the camera as the default and includes a child mesh. The component wraps the THREE.OrthographicCamera API.
```jsx
```
--------------------------------
### Injecting Properties into Clones
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/clone.mdx
Demonstrates how to use the inject prop to dynamically apply materials or conditional logic to cloned meshes.
```jsx
} />
```
```jsx
(object.name === 'table' ? : null)
} />
```
--------------------------------
### Nested Instances and Global Helpers
Source: https://github.com/pmndrs/drei/blob/master/docs/performances/instances.mdx
Using createInstances to manage multiple independent instance groups within the same scene graph. This is necessary when multiple instance providers are nested or need to be strictly separated.
```jsx
const [CubeInstances, Cube] = createInstances()
const [SphereInstances, Sphere] = createInstances()
function App() {
return (
<>
>
)
}
```
--------------------------------
### Html Component Usage and Props
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/html.mdx
Demonstrates the basic usage of the Html component and its various props for customization. It covers element wrapping, positioning, scaling, z-index, portal targeting, transform modes, occlusion, and event handling. It also shows how to pass down THREE.Group and HTMLDivElement props.
```jsx
number[]} // Override default positioning function. (default=undefined) [ignored in transform mode]
occlude={[ref]} // Can be true or a Ref[], true occludes the entire scene (default: undefined)
onOcclude={(hidden) => null} // Callback when the visibility changes (default: undefined)
{...groupProps} // All THREE.Group props are valid
{...divProps} // All HTMLDivElement props are valid
>
hello
world
```
--------------------------------
### Get Iris Direction - TypeScript
Source: https://github.com/pmndrs/drei/blob/master/docs/shapes/facemesh.mdx
Demonstrates how to retrieve the world direction of the right iris using the `eyeRightRef` from the Facemesh API. This can be used for gaze tracking or other eye-related interactions.
```typescript
api.eyeRightRef.current.irisDirRef.current.localToWorld(new THREE.Vector3(0, 0, -1))
```
--------------------------------
### Environment Component with Preset
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/environment.mdx
Demonstrates the simplest usage of the Environment component by providing a 'preset' name. This method relies on CDNs and is not recommended for production.
```jsx
```
--------------------------------
### Basic Drei Import for React Three Fiber
Source: https://github.com/pmndrs/drei/blob/master/docs/getting-started/introduction.mdx
Demonstrates the basic import statement for commonly used components from the @react-three/drei library in a React Three Fiber application. This allows access to components like PerspectiveCamera and PositionalAudio.
```jsx
import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei'
```
--------------------------------
### AsciiRenderer Usage Example (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/ascii-renderer.mdx
Demonstrates the basic usage of the AsciiRenderer component within a React Three Fiber Canvas. This snippet shows how to include the AsciiRenderer to enable ASCII-based rendering of the scene.
```jsx
```
--------------------------------
### Using Fisheye Component - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/portals/fisheye.mdx
Example of how to use the Fisheye component within a React Three Fiber Canvas. It demonstrates passing children to the Fisheye component and includes OrbitControls for camera interaction.
```jsx
```
--------------------------------
### Create Studio Environments with Stage
Source: https://context7.com/pmndrs/drei/llms.txt
The Stage component automatically sets up lighting, shadows, and camera centering for 3D objects. It is ideal for product visualization and supports both preset configurations and custom light/shadow properties.
```jsx
import { Canvas } from '@react-three/fiber'
import { Stage, OrbitControls } from '@react-three/drei'
import { Suspense } from 'react'
function ProductViewer({ children }) {
return (
{children}
)
}
```
--------------------------------
### Basic Resolution Regulation Example
Source: https://github.com/pmndrs/drei/blob/master/docs/performances/performance-monitor.mdx
Demonstrates using PerformanceMonitor to regulate the device pixel ratio (dpr) of a Canvas. It adjusts dpr to 2 when performance is good (onIncline) and to 1 when performance degrades (onDecline).
```jsx
function App() {
const [dpr, setDpr] = useState(1.5)
return (
setDpr(2)} onDecline={() => setDpr(1)} />
```
--------------------------------
### VideoTexture Component Usage - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/video-texture-use-video-texture.mdx
Examples of using the `VideoTexture` component. The first shows using a render prop to access the texture for a material. The second demonstrates accessing the texture via a `useRef`.
```jsx
{(texture) => }
```
```jsx
const textureRef = useRef()
```
--------------------------------
### Render QuadraticBezierLine in React Three Fiber
Source: https://github.com/pmndrs/drei/blob/master/docs/shapes/quadratic-bezier-line.mdx
Demonstrates the basic usage of the QuadraticBezierLine component by defining start, end, and optional control points. It accepts standard THREE.Line2 and LineMaterial properties for styling.
```jsx
```
--------------------------------
### Initialize Default Controls
Source: https://github.com/pmndrs/drei/blob/master/docs/controls/introduction.mdx
Demonstrates how to instantiate a control component with the makeDefault prop, which registers the controls in the root store for global access.
```tsx
```
--------------------------------
### Render Nothing with MeshDiscardMaterial in JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/shaders/mesh-discard-material.mdx
This example demonstrates how to use MeshDiscardMaterial in JSX to hide an object while still rendering its shadows and child elements like Edges. It's a React component, implying a JSX environment.
```jsx
{/* Shadows and edges will show, but the model itself won't */}
```
--------------------------------
### Use Depth Buffer Hook Example - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/use-depth-buffer.mdx
Demonstrates how to use the useDepthBuffer hook in a React component. It takes optional 'size' and 'frames' arguments and returns a depthBuffer which can be passed to other components that require depth information.
```jsx
const depthBuffer = useDepthBuffer({
size: 256, // Size of the FBO, 256 by default
frames: Infinity, // How many frames it renders, Infinity by default
})
return
```
--------------------------------
### Declarative Mesh Sampling with Sampler
Source: https://github.com/pmndrs/drei/blob/master/docs/abstractions/sampler.mdx
Demonstrates how to scatter instances on a mesh surface by passing the mesh and instancedMesh as children to the Sampler component. It uses a weight attribute and a transform function to control the distribution of 1000 spheres.
```tsx
```
--------------------------------
### Runtime Caustics with Animated Light Source (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/caustics.mdx
Illustrates how to achieve runtime caustics by setting `frames` to `Infinity` and `resolution` to a lower value. It also demonstrates using a `useRef` hook to control and animate the `lightSource` position, providing dynamic lighting effects.
```jsx
const lightSource = useRef()
```
--------------------------------
### Render Realistic Contact Shadows
Source: https://context7.com/pmndrs/drei/llms.txt
ContactShadows creates soft, realistic shadows beneath objects without needing complex light setups. It supports performance optimizations like frame limiting for static scenes.
```jsx
import { Canvas } from '@react-three/fiber'
import { ContactShadows, OrbitControls } from '@react-three/drei'
function Scene() {
return (
)
}
```
--------------------------------
### Initialize useSurfaceSampler hook
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/use-surface-sampler.mdx
This hook retrieves sampling data from a target mesh. It accepts optional parameters for sample count, transformation logic, weighting, and an optional instanced mesh for direct scattering.
```javascript
const buffer = useSurfaceSampler(
mesh, // Mesh to sample
count, // [Optional] Number of samples (default: 16)
transform, // [Optional] Transformation function. Same as in
weight, // [Optional] Same as in
instancedMesh // [Optional] Instanced mesh to scatter
)
```
--------------------------------
### Render Cubic Bezier Line with Drei
Source: https://github.com/pmndrs/drei/blob/master/docs/shapes/cubic-bezier-line.mdx
This snippet demonstrates how to use the CubicBezierLine component to render a 3D line with customizable start, end, control points, color, and line width. It accepts all THREE.Line2 and THREE.LineMaterial props.
```jsx
```
--------------------------------
### Apply Box Projected Environment Mapping with React Three Drei
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/use-box-projected-env.mdx
This snippet demonstrates how to initialize the useBoxProjectedEnv hook with position and scale, and apply the resulting projection properties to a meshStandardMaterial. It is commonly used alongside CubeCamera to achieve realistic, low-cost reflections.
```jsx
const projection = useBoxProjectedEnv(
[0, 0, 0], // Position
[1, 1, 1] // Scale
)
{(texture) => (
)}
```
--------------------------------
### Use RandomizedLight Component (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/randomized-light.mdx
Demonstrates how to use the RandomizedLight component in JSX, configuring it with specific properties like shadow casting, light amount, frame count, and position. This example shows a practical application for dynamic lighting.
```jsx
```
--------------------------------
### Environment Component with Files
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/environment.mdx
Shows how to use the Environment component with the 'files' prop to load environment maps from various file formats including HDR, EXR, JPG, WEBP, and image arrays.
```jsx
```
--------------------------------
### Use useSpriteLoader with SpriteAnimator (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/use-sprite-loader.mdx
Demonstrates how to use the useSpriteLoader hook to load sprite assets and then utilize the returned sprite data with multiple SpriteAnimator components. This example shows loading multiple animations from a single sprite sheet.
```jsx
const { spriteObj } = useSpriteLoader(
'multiasset.png',
'multiasset.json',
['orange', 'Idle Blinking', '_Bat'],
null
)
```
--------------------------------
### Stage with Accumulative Shadows - JSX
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/stage.mdx
Illustrates how to configure the Stage component for more realistic results by enabling 'accumulative' shadows. This setup requires the Canvas and models to support shadows, typically by enabling the 'shadows' prop on the Canvas.
```jsx
```
--------------------------------
### Extend GLTF Loader
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/gltf-use-gltf.mdx
Demonstrates how to extend the GLTFLoader to support additional features like KTX2 textures by passing a callback to the useGLTF hook.
--------------------------------
### Implement Fbo Component
Source: https://github.com/pmndrs/drei/blob/master/docs/misc/fbo-use-fbo.mdx
The Fbo component provides a declarative way to create a render target. It supports a render prop pattern to access the target or can be accessed via a ref.
```tsx
export type FboProps = {
children?: (renderTarget: Fbo) => React.ReactNode
width?: UseFBOParams[0]
height?: UseFBOParams[1]
} & FBOSettings
```
```jsx
{(renderTarget) => (
)}
```
```jsx
const renderTargetRef = useRef()
```
--------------------------------
### iOS/Safari Black Video Workaround - TypeScript
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/video-texture-use-video-texture.mdx
A workaround for a known issue on iOS/Safari where videos with `start: false` might appear black. This code forces the video to play and then pause to ensure pixels are sent to the GPU texture.
```tsx
const texture = useVideoTexture(src, { start: false });
async function warmup(texture: THREE.VideoTexture) {
const video = texture.image as HTMLVideoElement;
await video.play();
setTimeout(() => {
video.pause();
video.currentTime = 0;
}, 0);
}
useEffect(() => {
warmup(texture).catch((err) => console.log("warmup failed", err));
}, [texture]);
```
--------------------------------
### Use Merged with Loaded Models (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/performances/merged.mdx
This example shows how to utilize the Merged component with loaded 3D models. By passing the 'nodes' object from useGLTF to Merged, you can render individual parts of the model as distinct components, each optimized for rendering efficiency.
```jsx
function Model({ url }) {
const { nodes } = useGLTF(url)
return (
{({ Screw, Filter, Pipe }) => (
<>
>
)}
)
}
```
--------------------------------
### Implement instanced clouds in React Three Fiber
Source: https://github.com/pmndrs/drei/blob/master/docs/staging/cloud.mdx
Demonstrates how to use the provider to group multiple components into a single, optimized instanced draw call.
```jsx
```
--------------------------------
### Create Box and Plane Meshes with Buffer Geometry Args (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/shapes/mesh.mdx
Demonstrates how to create Box and Plane meshes using Drei's JSX components. The 'args' prop directly maps to the buffer geometry constructor, and other mesh properties can be passed as spread attributes. It also shows how to set material properties directly.
```jsx
// Plane with buffer geometry args
// Box with color set on the default MeshBasicMaterial
// Sphere with a MeshStandardMaterial
```
--------------------------------
### Prop-based Segments Component Usage (JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/performances/segments.mdx
Demonstrates how to use the Segments component with prop-based segment definitions. It allows setting a limit for segments, line width, and material properties. Individual segments are defined with 'start', 'end', and 'color' props.
```jsx
```
--------------------------------
### Load and Render GLTF Models with useGLTF and Gltf
Source: https://context7.com/pmndrs/drei/llms.txt
Provides methods to load 3D models in GLTF/GLB format with automatic Draco decompression. Supports both a hook-based approach for fine-grained control over nodes and materials, and a component-based approach for direct scene rendering.
```jsx
import { Canvas } from '@react-three/fiber'
import { useGLTF, Gltf } from '@react-three/drei'
import { Suspense } from 'react'
// Preload model for better performance
useGLTF.preload('/models/robot.glb')
function Robot({ position }) {
const { scene, nodes, materials, animations } = useGLTF('/models/robot.glb')
return
}
function RobotWithCustomParts() {
const { nodes, materials } = useGLTF('/models/robot.glb')
return (
)
}
function Scene() {
return (
)
}
```
--------------------------------
### Preload Font with useFont.preload (React/JSX)
Source: https://github.com/pmndrs/drei/blob/master/docs/loaders/use-font.mdx
Demonstrates how to preload a font using the static preload method of the useFont hook. This is useful for ensuring fonts are available before they are needed, improving performance by avoiding runtime loading delays. The method accepts the font file path as an argument.
```jsx
useFont.preload('/fonts/helvetiker_regular.typeface.json')
```