react-spline

repository·main·Indexed 23 days ago

https://github.com/splinetool/react-spline

A React wrapper for Spline that allows developers to embed interactive 3D scenes into React applications. It provides the <Spline /> component to load .splinecode files, manipulate 3D objects via findObjectByName and findObjectById, and trigger or listen to scene events. The library includes specialized support for Next.js SSR via @splinetool/react-spline/next and provides an Application object for programmatic control over animations and zoom levels.

Tokens
5.7K
Snippets
10
Records
14
Agent score
31%

What's inside @splinetool/react-spline

  1. Read and modify Spline objects

    main

    You can interact with specific 3D objects within a scene by querying them via findObjectByName or findObjectById inside the onLoad callback. Once retrieved, you can manipulate their properties (like position, rotation, etc.) directly.

    import { useRef } from 'react';
    import Spline from '@splinetool/react-spline';
    
    export default function App() {
      const cube = useRef();
    
      function onLoad(spline) {
        const obj = spline.findObjectByName('Cube');
        // or
        // const obj = spline.findObjectById('8E8C2DDD-18B6-4C54-861D-7ED2519DE20E');
    
        // save it in a ref for later use
        cube.current = obj;
      }
    
      function moveObj() {
        console.log(cube.current); // Spline Object => { name: 'Cube', id: '8E8C2DDD-18B6-4C54-861D-7ED2519DE20E', position: {}, ... }
    
        // move the object in 3D space
        cube.current.position.x += 10;
      }
    
      return (
        <div>
          <Spline
            scene="https://prod.spline.design/6Wq1Q7YGyM-iab9i/scene.splinecode"
            onLoad={onLoad}
          />
          <button type="button" onClick={moveObj}>
            Move Cube
          </button>
        </div>
      );
    }
  2. Install @splinetool/react-spline

    main

    To use Spline scenes in your React application, you must install both @splinetool/react-spline and @splinetool/runtime.

    yarn add @splinetool/react-spline @splinetool/runtime

    or

    npm install @splinetool/react-spline @splinetool/runtime
  3. Use Spline with Next.js for SSR

    main

    To take advantage of Server Side Rendering in Next.js, import from @splinetool/react-spline/next instead of the default entry point. This will render an autogenerated blurred placeholder on the server while the actual scene renders on the client.

    import Spline from '@splinetool/react-spline/next';
    
    export default function App() {
      return (
        <div>
          <Spline scene="https://prod.spline.design/KFonZGtsoUXP-qx7/scene.splinecode" />
        </div>
      );
    }
  4. Basic Usage of the Spline Component

    main

    To display a Spline scene, export your scene from the Spline editor (Export > Code > React), copy the URL, and pass it to the scene prop of the <Spline /> component.

    Note on CORS: If you encounter CORS issues, download the .splinecode file from the Spline export panel and self-host it instead of using a remote URL.

    import Spline from '@splinetool/react-spline';
    
    export default function App() {
      return (
        <div>
          <Spline scene="https://prod.spline.design/6Wq1Q7YGyM-iab9i/scene.splinecode" />
        </div>
      );
    }
  5. Trigger Spline events from outside the scene

    main

    You can trigger animation events defined in the Spline editor from your React code using the emitEvent method. There are two ways to do this:

    1. Via the Spline App instance: Use the onLoad callback to save the splineApp instance to a ref, then call spline.current.emitEvent(eventType, objectId).
    2. Via a specific Spline Object: Use findObjectByName or findObjectById to get the object, then call object.emitEvent(eventType) on that object.
    import { useRef } from 'react';
    import Spline from '@splinetool/react-spline';
    
    export default function App() {
      const spline = useRef();
    
      function onLoad(splineApp) {
        // save the app in a ref for later use
        spline.current = splineApp;
      }
    
      function triggerAnimation() {
        spline.current.emitEvent('mouseHover', 'Cube');
      }
    
      return (
        <div>
          <Spline
            scene="https://prod.spline.design/6Wq1Q7YGyM-iab9i/scene.splinecode"
            onLoad={onLoad}
          />
          <button type="button" onClick={triggerAnimation}>
            Trigger Spline Animation
          </button>
        </div>
      );
    }
    import { useRef } from 'react';
    import Spline from '@splinetool/react-spline';
    
    export default function App() {
      const objectToAnimate = useRef();
    
      function onLoad(spline) {
        const obj = spline.findObjectByName('Cube');
        // save the object in a ref for later use
        objectToAnimate.current = obj;
      }
    
      function triggerAnimation() {
        objectToAnimate.current.emitEvent('mouseHover');
      }
    
      return (
        <div>
          <Spline
            scene="https://prod.spline.design/6Wq1Q7YGyM-iab9i/scene.splinecode"
            onLoad={onLoad}
          />
          <button type="button" onClick={triggerAnimation}>
            Trigger Spline Animation
          </button>
        </div>
      );
    }
  6. Listen to Spline Events

    main

    You can listen to events defined in the Spline editor (e.g., mouse clicks) by attaching corresponding event handlers to the <Spline /> component. The event object e provides access to the target object, allowing you to check which object triggered the event via e.target.name.

    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 (
        <Spline
          scene="https://prod.spline.design/6Wq1Q7YGyM-iab9i/scene.splinecode"
          onSplineMouseDown={onSplineMouseDown}
        />
      );
    }
  7. Lazy load the Spline component

    main

    To prevent the Spline runtime from blocking the initial page load, you can use React.lazy and Suspense to load the component dynamically.

    import React, { Suspense } from 'react';
    
    const Spline = React.lazy(() => import('@splinetool/react-spline'));
    
    export default function App() {
      return (
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <Spline scene="https://prod.spline.design/6Wq1Q7YGyM-iab9i/scene.splinecode" />
          </Suspense>
        </div>
      );
    }
  8. Spline App Methods

    main

    The Application object, provided as the first argument to the onLoad prop, allows you to manipulate the Spline scene.

    Available methods:

    • emitEvent(eventName, nameOrUuid): Triggers a specific Spline event on an object identified by its name or UUID.
    • emitEventReverse(eventName, nameOrUuid): Triggers a Spline event in reverse order (from last state to first state).
    • findObjectById(uuid): Returns the SPEObject matching the provided UUID.
    • findObjectByName(name): Returns the first SPEObject matching the provided name.
    • setZoom(zoom): Sets the initial zoom level of the scene.
    | Name               | Type                                                                                                                 |
    | ------------------ | ---------------------------------------------------------------------------------------------------------------------|
    | `emitEvent`        | `(eventName: SplineEventName, nameOrUuid: string) => void` | Triggers a Spline event associated to an object with provided name or uuid. |
    | `emitEventReverse` | `(eventName: SplineEventName, nameOrUuid: string) => void` | Triggers a Spline event associated to an object with provided uuid in reverse order. Starts from last state to first state. |
    | `findObjectById`   | `(uuid: string) => SPEObject`                              | Searches through scene's children and returns the object with that uuid. |
    | `findObjectByName` | `(name: string) => SPEObject`                              | Searches through scene's children and returns the first object with that name. |
    | `setZoom`          | `(zoom: number) => void`                                   | Sets the initial zoom of the scene. |
  9. Spline Component Props

    main

    The <Spline /> component accepts several props to control scene loading, rendering behavior, and event handling.

    Key props include:

    • scene: The URL or path to the Spline scene file.
    • onLoad: A callback function executed once the scene is loaded. It receives an instance of the Application object, which allows you to interact with the scene programmatically.
    • renderOnDemand: A boolean to enable/disable on-demand rendering (defaults to true).
    • onSpline[EventName]: Specific event handlers for Spline events like MouseDown, MouseUp, KeyDown, Start, etc.

    Standard React props like className, style, id, and ref are also supported.

    | Name                  | Type                            | Description                                                                                                                   |
    | --------------------- | ------------------------------- | -----------------------------------------------------------------------------------------------------------------------------|
    | `scene`               | `string`                        | Scene file                                                                                                                    |
    | `onLoad?`             | `(spline: Application) => void` | Gets called once the scene has loaded. The `spline` parameter is an instance of the [Spline Application](#spline-app-methods) |
    | `renderOnDemand?`     | `boolean`                       | Wether or not to enable [on demand rendering](https://threejs.org/manual/#en/rendering-on-demand). Default `true`.            |
    | `className?`          | `string`                        | CSS classes                                                                                                                   |
    | `style?`              | `object`                        | CSS style                                                                                                                     |
    | `id?`                 | `string`                        | Canvas id                                                                                                                     |
    | `ref?`                 | `React.Ref<HTMLDivElement>`     | A ref pointing to div container element.                                                                                      |
    | `onSplineMouseDown?`  | `(e: SplineEvent) => void`      | Gets called once a Spline `Mouse Down` event is fired                                                                         |
    | `onSplineMouseHover?` | `(e: SplineEvent) => void`      | Gets called once a Spline `Mouse Hover` event is fired                                                                        |
    | `onSplineMouseUp?`    | `(e: SplineEvent) => void`      | Gets called once a Spline `Mouse Up` event is fired                                                                           |
    | `onSplineKeyDown?`    | `(e: SplineEvent) => void`      | Gets called once a Spline `Key Down` event is fired                                                                           |
    | `onSplineKeyUp?`      | `(e: SplineEvent) => void`      | Gets called once a Spline `Key Up` event is fired                                                                             |
    | `onSplineStart?`      | `(e: SplineEvent) => void`      | Gets called once a Spline `Start` event is fired                                                                              |
    | `onSplineLookAt?`     | `(e: SplineEvent) => void`      | Gets called once a Spline `Look At` event is fired                                                                           |
    | `onSplineFollow?`     | `(e: SplineEvent) => void`      | Gets called once a Spline `Mouse Up` event is fired                                                                           |
    | `onSplineScroll?`     | `(e: SplineEvent) => void`      | Gets called once a Spline `Scroll` event is fired                                                                             |
  10. Spline Event Types

    main

    When using emitEvent or emitEventReverse on a Spline Application instance, you can pass the following event names to trigger specific behaviors defined in your Spline scene:

    • mouseDown
    • mouseHover
    • mouseUp
    • keyDown
    • keyUp
    • start
    • lookAt
    • follow
    | Name         | Description                                                                    |
    | ------------ | ------------------------------------------------------------------------------|
    | `mouseDown`  | Refers to the Spline `Mouse Down` event type                                   |
    | `mouseHover` | Refers to the Spline `Mouse Hover` event type                                   |
    | `mouseUp`    | Refers to the Spline `Mouse Up` event type                                    |
    | `keyDown`    | Refers to the Spline `Key Down` event type                                     |
    | `keyUp`      | Refers to the Spline `Key Up` event type                                       |
    | `start`      | Refers to the Spline `Start` event type                                       |
    | `lookAt`     | Refers to the Spline `Look At` event type                                     |
    | `follow`     | Refers to the Spline `Mouse Up` event type                                     |
  11. Use the Spline component

    main
    The Spline component is the primary entry point for integrating Spline scenes into a React application. It accepts a scene URL and provides hooks for lifecycle events and Spline-specific interactions. By default, it uses renderOnDemand mode to optimize performance.
  12. Configure SplineProps

    main

    The SplineProps interface defines the configuration for the Spline component:

    • scene (string): The URL to the .splinecode file.
    • onLoad (function): Callback triggered when the Spline application is fully loaded. Receives the Application instance as an argument.
    • renderOnDemand (boolean): If true, the scene only renders when needed. Defaults to true.
    • wasmPath (string): Optional path to the WebAssembly (.wasm) file.
    • onSpline[EventName] (function): Event listeners for Spline interactions (see 'Spline Event Handlers' below).
    • style (React.CSSProperties): Standard CSS styles for the container.