### Install, Develop, Build, and Publish with Yarn Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/project-overview.md Standard Yarn commands for managing the project lifecycle, including dependency installation, starting the development server, building for production, and publishing to npm. ```bash # Install dependencies yarn install # Start dev server (serves example) yarn dev # Build for production yarn build # Publish to npm yarn publish ``` -------------------------------- ### Start Development Server Source: https://github.com/splinetool/react-spline/blob/main/README.md Serve the example folder at localhost:3000 for development. This command is used to test changes locally. ```bash yarn dev ``` -------------------------------- ### Install react-spline with Yarn Source: https://github.com/splinetool/react-spline/blob/main/README.md Install the react-spline and @splinetool/runtime packages using Yarn. ```bash yarn add @splinetool/react-spline @splinetool/runtime ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/splinetool/react-spline/blob/main/README.md Install project dependencies using yarn. This command should be run after cloning the repository. ```bash yarn ``` -------------------------------- ### Full Usage Example Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-application.md A comprehensive example demonstrating the full usage of the React Spline component, including event handling and state management. ```APIDOC ## Full Usage Example ```typescript import Spline, { type Application, type SplineEvent } from '@splinetool/react-spline'; import { useRef, useState } from 'react'; export const InteractiveScene = () => { const appRef = useRef(null); const [selectedObject, setSelectedObject] = useState(null); const [zoom, setZoom] = useState(1); const handleLoad = (app: Application) => { appRef.current = app; // Set initial state app.setZoom(1); // Add listener for mouse clicks app.addEventListener('mouseDown', (e) => { console.log('Clicked:', e.target.name); setSelectedObject(e.target.name); }); }; const handleMouseDown = (e: SplineEvent) => { console.log('Event:', e.target.name); }; const rotateObject = () => { if (!appRef.current || !selectedObject) return; const obj = appRef.current.findObjectByName(selectedObject); if (obj) { obj.rotation.y += Math.PI / 4; } }; const triggerAnimation = () => { if (!appRef.current || !selectedObject) return; appRef.current.emitEvent('mouseHover', selectedObject); }; const reverseAnimation = () => { if (!appRef.current || !selectedObject) return; appRef.current.emitEventReverse('mouseHover', selectedObject); }; const handleZoom = (value: number) => { if (appRef.current) { appRef.current.setZoom(value); setZoom(value); } }; return (

Selected: {selectedObject || 'None'}

); }; ``` ``` -------------------------------- ### Install React Spline Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/00-START-HERE.md Install the React Spline package and its peer dependencies using npm. ```bash npm install @splinetool/react-spline @splinetool/runtime react react-dom ``` -------------------------------- ### Install React Spline and Dependencies Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Install the core React Spline package along with its runtime and essential React libraries. For Next.js projects, also install the Next.js package. ```bash npm install @splinetool/react-spline @splinetool/runtime react react-dom # For Next.js support npm install next ``` -------------------------------- ### Minimal Spline Scene Setup Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/usage-patterns.md Renders the simplest possible Spline scene. Ensure the scene URL is correct. ```typescript import Spline from '@splinetool/react-spline'; export default function BasicScene() { return (
); } ``` -------------------------------- ### React Setup with Type Annotations Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/module-reference.md Utilize type annotations for SplineProps and Application when configuring the Spline component, including an onLoad callback. ```typescript import Spline, { type SplineProps, type Application } from '@splinetool/react-spline'; const config: SplineProps = { scene: 'https://...', onLoad: (app: Application) => { console.log('Loaded'); }, }; export const TypedScene = () => ; ``` -------------------------------- ### ResponsiveComponent with ParentSize Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md Example of using the ParentSize component to create a responsive element that adapts to its container's dimensions. It demonstrates passing a custom ResizeObserverPolyfill. ```typescript import ResizeObserverPolyfill from 'resize-observer-polyfill'; import ParentSize from '@splinetool/react-spline'; export const ResponsiveComponent = () => { return ( {({ width, height }) => (
{width} × {height}
)}
); }; ``` -------------------------------- ### Manual Resize Trigger Example Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-parentsize.md This example demonstrates how to manually trigger a resize event for the ParentSize component. A ref is used to access the `resize` function provided by ParentSize, allowing external elements like buttons to initiate a resize. ```typescript import { useRef } from 'react'; import ParentSize from './ParentSize'; export default function ManualResizeExample() { const manualResizeRef = useRef<(state: any) => void>(null); return (
{({ width, height, resize }) => { manualResizeRef.current = resize; return (

Width: {width}px, Height: {height}px

); }}
); } ``` -------------------------------- ### Spline Component Usage Example Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md Demonstrates how to import and use the `Spline` component with its props, including scene URL and an onLoad callback. Ensure necessary types are imported. ```typescript import Spline from '@splinetool/react-spline'; import type { SplineProps } from '@splinetool/react-spline'; const props: SplineProps = { scene: 'https://prod.spline.design/...', onLoad: (app) => console.log('Scene loaded'), renderOnDemand: true, }; export const MyScene = () => ; ``` -------------------------------- ### Full React Spline Usage Example Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-application.md Demonstrates a comprehensive example of using the Spline component in a React application. It includes scene loading, event handling for mouse interactions, object manipulation (rotation), animation control, and zoom functionality. ```typescript import Spline, { type Application, type SplineEvent } from '@splinetool/react-spline'; import { useRef, useState } from 'react'; export const InteractiveScene = () => { const appRef = useRef(null); const [selectedObject, setSelectedObject] = useState(null); const [zoom, setZoom] = useState(1); const handleLoad = (app: Application) => { appRef.current = app; // Set initial state app.setZoom(1); // Add listener for mouse clicks app.addEventListener('mouseDown', (e) => { console.log('Clicked:', e.target.name); setSelectedObject(e.target.name); }); }; const handleMouseDown = (e: SplineEvent) => { console.log('Event:', e.target.name); }; const rotateObject = () => { if (!appRef.current || !selectedObject) return; const obj = appRef.current.findObjectByName(selectedObject); if (obj) { obj.rotation.y += Math.PI / 4; } }; const triggerAnimation = () => { if (!appRef.current || !selectedObject) return; appRef.current.emitEvent('mouseHover', selectedObject); }; const reverseAnimation = () => { if (!appRef.current || !selectedObject) return; appRef.current.emitEventReverse('mouseHover', selectedObject); }; const handleZoom = (value: number) => { if (appRef.current) { appRef.current.setZoom(value); setZoom(value); } }; return (

Selected: {selectedObject || 'None'}

); }; ``` -------------------------------- ### Basic Spline Component Setup Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/00-START-HERE.md Import and render the main Spline component with a scene URL. This is the most basic way to integrate Spline into a React application. ```typescript import Spline from '@splinetool/react-spline'; export default function App() { return ; } ``` -------------------------------- ### Production-Ready Next.js Setup Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Configure Spline for a Next.js application using the `@splinetool/react-spline/next` package. Ensure `NEXT_PUBLIC_SPLINE_SCENE_URL` is set in your environment variables. ```typescript // app/components/Scene.tsx 'use client'; import SplineNext from '@splinetool/react-spline/next'; import { type Application } from '@splinetool/react-spline'; import { useRef } from 'react'; export const Scene = () => { const appRef = useRef(null); return ( { appRef.current = app; }} renderOnDemand={true} className="w-full h-screen" /> ); }; ``` -------------------------------- ### Get Application Instance on Load Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-application.md Obtain the Application instance when a Spline scene finishes loading. This instance is used to interact with scene objects. ```typescript import Spline from '@splinetool/react-spline'; export const App = () => { const handleLoad = (app: Application) => { // app is the Application instance const obj = app.findObjectByName('Cube'); }; return ; }; ``` -------------------------------- ### Configure ParentSize Component Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Example demonstrating how to configure the ParentSize component with custom debounce time, ignored dimensions, inline styles, and a CSS class. The render function receives width and height to be used, for instance, in a canvas element. ```typescript import ParentSize from './ParentSize'; export const CustomResizeConfig = () => { return ( {({ width, height }) => ( )} ); }; ``` -------------------------------- ### ResizeObserverPolyfill Interface and Usage Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md The ResizeObserverPolyfill interface is designed for custom ResizeObserver implementations to ensure browser compatibility. The example demonstrates how to provide a custom ResizeObserver implementation to the ParentSize component. ```APIDOC ## ResizeObserverPolyfill Interface ### Description Interface for custom ResizeObserver implementations (for browser compatibility). ### Definition ```typescript interface ResizeObserverPolyfill { new (callback: ResizeObserverCallback): ResizeObserver; } ``` ### Usage ```typescript import ResizeObserverPolyfill from 'resize-observer-polyfill'; import ParentSize from '@splinetool/react-spline'; export const ResponsiveComponent = () => { return ( {({ width, height }) => (
{width} × {height}
)}
); }; ``` ``` -------------------------------- ### Interactive Scene with Event Handlers Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Integrate event handlers like `onSplineMouseDown` to make your scene interactive. This example tracks the selected object's name. ```typescript import Spline, { type Application } from '@splinetool/react-spline'; import { useRef, useState } from 'react'; export const InteractiveScene = () => { const appRef = useRef(null); const [selectedObject, setSelectedObject] = useState(null); return (
{ appRef.current = app; }} onSplineMouseDown={(e) => { setSelectedObject(e.target.name); }} />

Selected: {selectedObject || 'Nothing'}

); }; ``` -------------------------------- ### Decode BlurHash to Data URL with Custom Dimensions Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-decode-preview.md This example shows how to decode a BlurHash string into a data URL, with options to disable the alpha channel and specify custom width and height for the output image. ```typescript import { decodePreview } from '@splinetool/react-spline/next'; const blurHashStr = 'UeYUpOpIyZdy~VafQcp{'; // BlurHash string from server const dataUrl = decodePreview(blurHashStr, false, 1024, 768); // alpha = false, custom dimensions console.log(dataUrl); // 'data:image/png;base64,...' ``` -------------------------------- ### Spline Scene Controller Usage Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md Example of controlling a Spline scene using the Application object. It demonstrates finding objects, emitting events, and adjusting camera zoom. Ensure the Spline component is loaded with an onLoad handler to capture the Application instance. ```typescript import Spline, { type Application } from '@splinetool/react-spline'; import { useRef } from 'react'; export const SceneController = () => { const appRef = useRef(null); const handleLoad = (app: Application) => { appRef.current = app; }; const manipulateScene = () => { if (!appRef.current) return; // Find and modify objects const cube = appRef.current.findObjectByName('Cube'); if (cube) { cube.position.y += 10; } // Emit events appRef.current.emitEvent('mouseHover', 'Cube'); // Adjust camera appRef.current.setZoom(2); }; return ( <> ); }; ``` -------------------------------- ### Dynamic Zoom Control with React Spline Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/usage-patterns.md Implement dynamic zoom functionality for your Spline scene. This example uses a range input to control the camera's zoom level, requiring the `Application` type for type safety. ```typescript import Spline, { type Application } from '@splinetool/react-spline'; import { useRef } from 'react'; export default function ZoomControl() { const appRef = useRef(null); const handleLoad = (app: Application) => { appRef.current = app; app.setZoom(1); // Set default zoom }; const handleZoomChange = (e: React.ChangeEvent) => { const zoom = parseFloat(e.target.value); appRef.current?.setZoom(zoom); }; return (
); } ``` -------------------------------- ### Spline React and Next.js Exports Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/README.md Demonstrates the main export for using Spline in a React application and the specific export for Next.js server components. Ensure you have the correct imports based on your project setup. ```typescript // Main export import Spline, { type SplineProps, type SPEObject, type SplineEvent, type SplineEventName } from '@splinetool/react-spline'; // Next.js export (server component) import SplineNext from '@splinetool/react-spline/next'; ``` -------------------------------- ### Emitting Custom Events with SplineEventName Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md This example shows how to emit specific Spline events using the SplineEventName type and the emitEvent method. It requires a ref to the Spline component and a way to trigger the emission, such as a button click. ```typescript import Spline, { type SplineEventName } from '@splinetool/react-spline'; import { useRef } from 'react'; export const EventEmitter = () => { const appRef = useRef(null); const triggerEvent = (eventName: SplineEventName) => { if (appRef.current) { appRef.current.emitEvent(eventName, 'Cube'); } }; return ( <> { appRef.current = app; }} /> ); }; ``` -------------------------------- ### Advanced Spline Component for Dynamic Manipulation Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-spline-component.md Shows how to dynamically manipulate a Spline scene in React. This example allows rotating objects and triggering animations via button clicks, utilizing a ref to access the Spline application instance. ```typescript import { useRef } from 'react'; import Spline, { type Application } from '@splinetool/react-spline'; export default function AnimatedScene() { const appRef = useRef(null); function handleLoad(app: Application) { appRef.current = app; } function rotateObject(objectName: string) { if (!appRef.current) return; const obj = appRef.current.findObjectByName(objectName); if (obj) { obj.rotation.y += Math.PI / 4; } } function triggerAnimation(objectId: string) { if (!appRef.current) return; appRef.current.emitEvent('mouseHover', objectId); } return ( <> ); } ``` -------------------------------- ### Project Structure: Source Files Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/project-overview.md Illustrates the directory structure of the react-spline library's source code. ```tree react-spline/ ├── src/ │ ├── Spline.tsx # Main React component │ ├── ParentSize.tsx # Responsive sizing wrapper │ └── next/ │ ├── SplineNext.tsx # Next.js SSR component │ └── decodePreview.ts # Preview image decoding ├── package.json # Package configuration ├── tsconfig.json # TypeScript configuration ├── vite.config.ts # Vite build configuration └── README.md # User documentation ``` -------------------------------- ### Basic Responsive Container with ParentSize Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-parentsize.md Demonstrates how to use the ParentSize component to create a responsive container that displays its current dimensions. It sets a debounce time of 100ms for resize events. ```typescript import ParentSize from './ParentSize'; export default function ResponsiveBox() { return ( {({ width, height, ref }) => (

Container size: {width.toFixed(0)}px × {height.toFixed(0)}px

)}
); } ``` -------------------------------- ### Preview Caching Strategy Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Set the cache option for fetching preview metadata. Use 'force-cache' in production for indefinite caching and 'no-store' in development for fresh fetches. ```typescript const cache = process.env.NODE_ENV === 'production' ? 'force-cache' : 'no-store'; await fetch(`https://${scope}.spline.design/${id}/hash`, { cache }); ``` -------------------------------- ### SplineEventName Type Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md The SplineEventName type is a union of all valid event names that can be emitted or listened to. This includes events like 'mouseDown', 'mouseHover', 'keyDown', and 'start'. ```APIDOC ## SplineEventName Type ### Description Union type of all valid event names that can be emitted or listened to in Spline. ### Definition ```typescript export type SplineEventName = | 'mouseDown' | 'mouseUp' | 'mouseHover' | 'keyDown' | 'keyUp' | 'start' | 'lookAt' | 'follow' | 'scroll'; ``` ### Valid Values | Event Name | |-----------| | `'mouseDown'` | | `'mouseUp'` | | `'mouseHover'` | | `'keyDown'` | | `'keyUp'` | | `'start'` | | `'lookAt'` | | `'follow'` | | `'scroll'` | ### Usage Example ```typescript import Spline, { type SplineEventName } from '@splinetool/react-spline'; import { useRef } from 'react'; export const EventEmitter = () => { const appRef = useRef(null); const triggerEvent = (eventName: SplineEventName) => { if (appRef.current) { appRef.current.emitEvent(eventName, 'Cube'); } }; return ( <> { appRef.current = app; }} /> ); }; ``` ``` -------------------------------- ### Publish on npm Source: https://github.com/splinetool/react-spline/blob/main/README.md Publish the library to npm. This command is typically used by maintainers to release new versions. ```bash yarn publish ``` -------------------------------- ### Project Structure: Build Output Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/project-overview.md Details the output structure of the react-spline library after the build process. ```tree dist/ ├── react-spline.js # Main bundle (ES module) ├── react-spline-next.js # Next.js bundle (ES module) ├── Spline.d.ts # Type definitions └── next/ └── SplineNext.d.ts # Next.js type definitions ``` -------------------------------- ### Trigger Spline Event Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-application.md Programmatically triggers a Spline event on a target object by its name or UUID. This is useful for starting animations or behaviors defined in the Spline editor. ```typescript const handleLoad = (app: Application) => { // Find object for later use const cube = app.findObjectByName('Cube'); }; const triggerAnimation = (app: Application) => { // Trigger hover animation on the cube app.emitEvent('mouseHover', 'Cube'); // Or trigger using UUID app.emitEvent('mouseHover', '8E8C2DDD-18B6-4C54-861D-7ED2519DE20E'); }; return ( <> ); ``` -------------------------------- ### Using ResizeObserver Polyfill with ParentSize Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-parentsize.md Provide a custom ResizeObserver implementation using the `resizeObserverPolyfill` prop for compatibility with older browsers. ```typescript import ResizeObserverPolyfill from 'resize-observer-polyfill'; {({ width, height }) => ...} ``` -------------------------------- ### Basic Usage Source: https://github.com/splinetool/react-spline/blob/main/README.md Demonstrates how to embed a Spline scene into a React component using the `` component. ```APIDOC ## Basic Usage ### Description Embed a Spline scene into your React application by providing the scene URL to the `` component. ### Method React Component ### Endpoint N/A ### Parameters #### Props - **scene** (string) - Required - The URL of the Spline scene to load. ### Request Example ```jsx import Spline from '@splinetool/react-spline'; export default function App() { return (
); } ``` ### Response #### Success Response - Renders the Spline scene within the React component. #### Response Example N/A ``` -------------------------------- ### Build Command for React Spline Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/module-reference.md This command is used to compile the library into distribution files. It first removes the existing 'dist' directory, then builds the JavaScript bundles using Vite, and finally generates the type definition files. ```bash yarn build # Runs: rimraf dist/ && vite build && yarn build-types # Generates all .js and .d.ts files ``` -------------------------------- ### Trigger Animations from Buttons in React Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/usage-patterns.md Use `emitEvent` to trigger animations defined in your Spline scene. Ensure the Spline component's `onLoad` handler is used to get a reference to the application instance. ```typescript import Spline, { type Application } from '@splinetool/react-spline'; import { useRef } from 'react'; export default function AnimationTrigger() { const appRef = useRef(null); const handleLoad = (app: Application) => { appRef.current = app; }; const triggerAnimation = (objectName: string, eventName: string) => { const app = appRef.current; if (!app) return; app.emitEvent(eventName as any, objectName); }; return (
); } ``` -------------------------------- ### Listening to Spline Events Source: https://github.com/splinetool/react-spline/blob/main/README.md Demonstrates how to listen for and respond to events originating from the Spline scene, such as mouse interactions. ```APIDOC ## Listening to Spline Events ### Description Attach event listeners to the `` component to react to user interactions or events defined within the Spline editor. Event handlers receive an event object containing details about the interaction. ### Method React Component with Event Listeners ### Endpoint N/A ### Parameters #### Props - **scene** (string) - Required - The URL of the Spline scene. - **onSplineMouseDown** (function) - Optional - Callback for mouse down events on Spline objects. - Other Spline events (e.g., `onSplineClick`, `onSplineHover`) are also available. ### Request Example ```jsx import Spline from '@splinetool/react-spline'; export default function App() { function onSplineMouseDown(e) { if (e.target.name === 'Cube') { console.log('I have been clicked!'); } } return (
); } ``` ### Response #### Success Response - Event handlers are triggered based on user interactions within the Spline scene. #### Response Example ```json { "example": "I have been clicked!" } ``` ``` -------------------------------- ### Build React Spline Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/00-START-HERE.md Build the React Spline library using yarn. This command outputs the build to the dist/ directory. ```bash yarn build ``` -------------------------------- ### Event-Driven Interaction with React Spline Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/project-overview.md Handle user interactions within the Spline scene by attaching event listeners to the Spline component. This example demonstrates logging a message when a specific object, like a 'Button', is clicked. ```typescript import Spline from '@splinetool/react-spline'; export default function App() { function handleClick(e) { if (e.target.name === 'Button') { console.log('Button clicked!'); } } return ( ); } ``` -------------------------------- ### Accessing the Wrapper Div with useRef Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-spline-component.md Use `useRef` to get a reference to the wrapper div element of the Spline component. The canvas element is not directly exposed; interact with the scene via the `Application` instance provided in `onLoad`. ```typescript const divRef = useRef(null); // Access the div: divRef.current ``` -------------------------------- ### ParentSize Component Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/README.md An internal responsive sizing wrapper component used for measuring dimensions and integrating with ResizeObserver, with configurable debounce. ```APIDOC ## ParentSize Component ### Description Internal responsive sizing wrapper component used for measuring dimensions and integrating with ResizeObserver, with configurable debounce. ### Features - Dimension measurement. - Debounce configuration. - ResizeObserver integration. ``` -------------------------------- ### Next.js Integration Source: https://github.com/splinetool/react-spline/blob/main/README.md Shows how to use react-spline with Next.js, including server-side rendering with a blurred placeholder. ```APIDOC ## Next.js Integration ### Description Integrate Spline scenes into Next.js applications. Using `@splinetool/react/next` enables server-side rendering with an autogenerated blurred placeholder. ### Method React Component (Next.js) ### Endpoint N/A ### Parameters #### Props - **scene** (string) - Required - The URL of the Spline scene to load. ### Request Example ```js import Spline from '@splinetool/react-spline/next'; export default function App() { return (
); } ``` ### Response #### Success Response - Renders the Spline scene with a blurred placeholder on the server and the full scene on the client. #### Response Example N/A ``` -------------------------------- ### Configure Spline Scene URL with Environment Variables Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-spline-next.md Manage Spline scene URLs using Next.js environment variables for better configuration management, especially in production environments. ```typescript const sceneUrl = process.env.NEXT_PUBLIC_SPLINE_SCENE_URL; ``` -------------------------------- ### Configure Spline Component with Options Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Demonstrates how to configure the Spline component with various props including scene URL, event handlers, rendering options, and DOM attributes. Use this to customize scene loading, interaction, and appearance. ```typescript import Spline from '@splinetool/react-spline'; export const ConfiguredScene = () => { const handleSceneLoaded = (app) => { console.log('Scene ready for interaction'); const cube = app.findObjectByName('Cube'); if (cube) { cube.scale.x = 1.2; } }; const handleMouseDown = (event) => { console.log(`Clicked: ${event.target.name}`); }; return ( ); }; ``` -------------------------------- ### Basic Spline Component Usage Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-spline-component.md Demonstrates how to embed a Spline 3D scene in a React application. It includes event handlers for scene loading and mouse interactions, and enables rendering on demand. ```typescript import { useRef } from 'react'; import Spline from '@splinetool/react-spline'; export default function App() { const splineRef = useRef(null); function handleLoad(app: Application) { console.log('Scene loaded!', app); // Interact with the application instance const cube = app.findObjectByName('Cube'); if (cube) { cube.position.x += 5; } } function handleMouseDown(event: SplineEvent) { console.log('Clicked object:', event.target.name); } return (
Loading 3D scene...
); } ``` -------------------------------- ### Environment Variable for Scene URL Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/configuration.md Manage scene URLs using Next.js environment variables for dynamic scene loading. Ensure the variable is prefixed with NEXT_PUBLIC_ to be available client-side if needed. ```bash # .env.local NEXT_PUBLIC_SPLINE_SCENE_URL=https://prod.spline.design/YOUR_ID/scene.splinecode ``` -------------------------------- ### Application Methods Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/project-overview.md Methods available on the Spline application instance for interacting with the loaded 3D scene. ```APIDOC ## Application Methods These methods are available on the `Application` instance, which can be accessed via the `onLoad` callback of the `Spline` component or by using `useRef`. ### `findObjectByName(name: string): SPEObject` Finds and returns a 3D object in the scene by its name. ### `findObjectById(id: string): SPEObject` Finds and returns a 3D object in the scene by its unique ID. ### `emitEvent(eventName: SplineEventName, nameOrUuid: string): void` Emits a specified event on a target object identified by its name or UUID. ### `emitEventReverse(eventName: SplineEventName, nameOrUuid: string): void` Emits a specified event in reverse on a target object identified by its name or UUID. ### `setZoom(zoom: number): void` Sets the zoom level of the scene camera. ### `addEventListener(name: SplineEventName, callback: (e: SplineEvent) => void): void` Adds a listener for a specific Spline event. ### `removeEventListener(name: SplineEventName, callback: (e: SplineEvent) => void): void` Removes a previously added event listener. ### `load(url: string): Promise` Loads a new Spline scene from the given URL. ### `dispose(): void` Cleans up and disposes of the Spline application instance, releasing resources. ``` -------------------------------- ### Decode Preview with Error Handling Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-decode-preview.md Safely decode a preview hash using decodePreview and handle potential errors with a try-catch block. This is recommended for production robustness. ```typescript let dataUrl: string | undefined; try { dataUrl = decodePreview(hash, alpha, width, height); } catch (e) { console.error('Failed to decode preview:', e); // Fall back to no preview } ``` -------------------------------- ### Application Methods Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/README.md Provides methods for controlling the Spline scene, such as finding objects, emitting events, and adjusting zoom. These methods are part of the scene control interface from `@splinetool/runtime`. ```APIDOC ## Application Methods ### Description Provides methods for controlling the Spline scene, such as finding objects, emitting events, and adjusting zoom. These methods are part of the scene control interface from `@splinetool/runtime`. ### Methods - `findObjectByName(name: string): SPEObject` - `findObjectById(uuid: string): SPEObject` - `emitEvent(eventName: SplineEventName, nameOrUuid: string): void` - `emitEventReverse(eventName: SplineEventName, nameOrUuid: string): void` - `setZoom(zoom: number): void` - `addEventListener()` - `removeEventListener()` - `dispose()` - `load()` ``` -------------------------------- ### Implement Server-Side Rendering with Next.js Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/project-overview.md For Next.js applications, import the 'SplineNext' component for automatic preview generation during server rendering, including a blur placeholder for improved perceived performance. ```typescript import SplineNext from '@splinetool/react-spline/next'; ``` -------------------------------- ### Basic Next.js Page with SplineNext Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-spline-next.md Demonstrates the fundamental usage of the SplineNext component within a Next.js page. Ensure the scene URL is correctly formatted. ```typescript import SplineNext from '@splinetool/react-spline/next'; export default function Page() { return (
); } ``` -------------------------------- ### ParentSizeProps Interface Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md Configuration object for the ParentSize responsive sizing component. It defines the props that can be passed to customize its behavior and rendering. ```APIDOC ## ParentSizeProps Interface ### Description Configuration object for the `ParentSize` responsive sizing component. ### Properties #### `children` - **Type**: `(args) => React.ReactNode` - **Required**: yes - **Description**: Render function receiving dimension data. #### `className` - **Type**: `string` - **Required**: no - **Description**: CSS class for wrapper div. #### `debounceTime` - **Type**: `number` - **Required**: no - **Description**: Resize event debounce delay in ms (default: 300). #### `enableDebounceLeadingCall` - **Type**: `boolean` - **Required**: no - **Description**: Fire callback on first resize (default: true). #### `ignoreDimensions` - **Type**: `'width' | 'height' | 'top' | 'left' | array` - **Required**: no - **Description**: Dimension(s) to ignore for updates. #### `parentSizeStyles` - **Type**: `React.CSSProperties` - **Required**: no - **Description**: Inline styles for wrapper (default: 100% width/height). #### `resizeObserverPolyfill` - **Type**: `ResizeObserverPolyfill` - **Required**: no - **Description**: Custom ResizeObserver implementation. ``` -------------------------------- ### ParentSize Component Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/api-reference-parentsize.md A responsive sizing wrapper component that observes parent dimensions and debounces resize events. It passes the measured width, height, top, and left positions to its children through a render function. ```APIDOC ## ParentSize (Component) A responsive sizing wrapper that observes parent dimensions and debounces resize events. ### Signature ```typescript const ParentSize = forwardRef( (props: ParentSizeProps & Omit, keyof ParentSizeProps>, ref) => ReactElement ); ``` ### Props (ParentSizeProps Interface) | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `children` | `(args: { ref: HTMLDivElement | null; width: number; height: number; top: number; left: number; resize: (state: ParentSizeState) => void }) => React.ReactNode` | yes | — | Render function that receives measured dimensions and positioning. The function is called with an object containing `width`, `height`, `top`, `left`, `ref`, and a `resize` callback. | | `className` | `string` | no | — | CSS class name(s) to apply to the wrapper `div`. | | `parentSizeStyles` | `React.CSSProperties` | no | `{ width: '100%', height: '100%' }` | Inline CSS styles for the wrapper `div`. Default styles make it fill 100% of parent width and height. Can be overridden or extended. | | `debounceTime` | `number` | no | `300` | Delay in milliseconds before the resize callback is invoked after a resize event is detected. Prevents excessive re-renders during resizing. | | `enableDebounceLeadingCall` | `boolean` | no | `true` | When `true`, the resize callback fires immediately on the first resize event (leading edge), then respects the debounce delay for subsequent events. | | `ignoreDimensions` | `keyof ParentSizeState | (keyof ParentSizeState)[]` | no | `[]` | Dimension key(s) to ignore when determining if state has changed. Acceptable values: `'width'`, `'height'`, `'top'`, `'left'`. If a dimension is ignored, changes to it will not trigger state updates. | | `resizeObserverPolyfill` | `ResizeObserverPolyfill` | no | — | Optional custom ResizeObserver implementation. If not provided, uses the native `window.ResizeObserver`. Useful for environments where ResizeObserver is not available. | | `...restProps` | `React.HTMLAttributes` | no | — | Standard HTML div attributes (data-*, aria-*, event handlers, etc.) passed to the wrapper `div` element. | ### Child Render Function Parameters The `children` prop receives a single object argument with the following structure: ```typescript { width: number; // Current width of the container in pixels height: number; // Current height of the container in pixels top: number; // Distance from viewport top to container top left: number; // Distance from viewport left to container left ref: HTMLDivElement | null; // Reference to the wrapper div element resize: (state: ParentSizeState) => void; // Manual resize trigger function } ``` ### Return Type Returns a wrapper `div` element containing the rendered children. ### Behavior 1. **Dimension Measurement**: On mount, creates a ResizeObserver that monitors the wrapper `div` 2. **Resize Handling**: When resize events occur: - Calculates new `width`, `height`, `top`, and `left` from the ResizeObserver entry - Schedules a resize via `requestAnimationFrame` for smooth updates - Applies debouncing with the specified `debounceTime` and `enableDebounceLeadingCall` settings 3. **State Update**: Updates state only if the dimension changes (unless ignored via `ignoreDimensions`) 4. **Cleanup**: On unmount, cancels pending animation frames, disconnects the observer, and cancels debounce ### Internal State ```typescript type ParentSizeState = { width: number; height: number; top: number; left: number; }; ``` ### Example Usage: Basic Responsive Container ```typescript import ParentSize from './ParentSize'; export default function ResponsiveBox() { return ( {({ width, height, ref, }) => (

Container size: {width.toFixed(0)}px × {height.toFixed(0)}px

)}
); } ``` ``` -------------------------------- ### Import Spline Application Type Source: https://github.com/splinetool/react-spline/blob/main/_autodocs/types.md Import the Application type from the Spline runtime library. ```typescript import { Application } from '@splinetool/runtime'; ```