react-three-paper

A paper-thin (~800 bytes) and position-aware wrapper for ThreeJS in React.

Usage no npm install needed!

<script type="module">
  import reactThreePaper from 'https://cdn.skypack.dev/react-three-paper';
</script>

README


react-three-paper

A paper-thin (~800 bytes*) and position-aware wrapper for ThreeJS in React.
View Demo ยท Report Bug

My work is for and funded by the community. If you used this or found this helpful consider supporting me.


65k particles in React using Three.js via react-three-paper.


* Not including the Source Map and types.

But why?

I use this component a lot when creating React-based apps. A prominent example is my blog and I am kinda sick of rewriting it again and again.

But other than that, here are some actual uses over using something like react-three-fiber:

  • Very easily port Vanilla-JS scripts to React.
  • No special declarative syntax to learn.
  • Separate your UI logic from your core ThreeJS app.
  • It is TINY.

In theory, all you have to do to convert Vanilla-JS examples to React ones via this library is wrap them in a main() function, tell ThreeJS to render on the given canvas, and return the render loop as a function. Read more.

Position aware...what?

Yes, the canvas knows when it is out of the viewport and will pause your render loop. It will resume it when it is back in the viewport. This is TREMENDOUSLY helpful with performance.

For example, when creating long pages where you have multiple ThreeJS canvas components coming in and going out of the viewport.

You can also tap these events and define custom behavior.

Installation

npm install react-three-paper
# or
yarn add react-three-paper

react-three-paper requires react >=16.8.0

npm install react
# or
yarn add react

Usage

Import the Paper component and use it like this:

import { Paper } from "paper";
import { main } from "./main.js"; // ๐Ÿ‘ˆ Your ThreeJS script

export default function App() {
    return (
        <Paper 
            script={main} // ๐Ÿ‘ˆ Pass it in here
        />
    )
}

Your script

The script prop accepts a function, here is how that function should look.

export async function main(canvas) {
    //...Do ThreeJS stuff
    const renderer = new THREE.WebGLRenderer({
        canvas: canvas, // ๐Ÿ‘ˆ Use canvas as the ThreeJS canvas
    });

    // ๐Ÿ‘‡ Use canavs dimentions insted of window
    const aspectRatio = canvas.clientWidth / canvas.clientHeight;
    renderer.setSize(canvas.clientWidth, canvas.clientHeight);

    function render() {...} //...Render loop without requestAnimationFrame()
    function cleanup() {...} //...Any cleanup youd like (optional)

    return { render, cleanup }
}

Essentially, a function that receives a canvas element (that is used as the ThreeJS canvas) and returns a promise which resolves to a couple of functions.

  • render: Your render loop without requestAnimationFrame as this is handled by react-three-paper.
  • cleanup: An optional cleanup function without cancleAnimationFrame.

Pass this function directly into the script prop.

Example

An example app can be found within the example directory. It is also hosted here. See:

  • example/src/App.js: For Paper component usage.
  • example/src/three/main.js: For an example of how to format your main function.

Advanced Usage

Here are some other props that react-three-paper provides.

import { Paper } from "../../build/index";
import { main } from "./three/main.js";

export default function App() {
    return (
        <Paper 
            script={main}
            style={{...}} // ๐Ÿ‘ˆ CSS styles for the underlying <canvas>

            // ๐Ÿ‘‡ Events
            onExit={(entry, ID) => {...}} // ๐Ÿ‘ˆ Fired when canvas exits the viewport
            onEntry={(entry, ID) => {...}} // ๐Ÿ‘ˆ Fired when canvas enters the viewport
            onError={(error, ID) => {...}} // ๐Ÿ‘ˆ Fired when there is a error
        />
    )
}

| Prop | Required | Type | Discription | Default | |-|-|-|-|-| | script | Yes | tPaperScript | Your ThreeJS script | No default behaviour | | style | No | React.CSSProperties | CSS styles for the underlying <canvas> | Makes the canvas dimensions 100% of its container. | | onExit | No | tPaperPositionEvent | Fired when canvas exits the viewport | Stops the render loop when canvas exits viewport. | | onEntry | No | tPaperPositionEvent | Fired when canvas enters the viewport | Start the render loop when canvas enters viewport. | | onError | No | tPaperErrorEvent | Fired when there is a error | Logs the error and stops the render loop. |

Note: Default behaviour cannot be overwritten, only extended.

Types

tPaperRenderLoop

A function that receives current time. By default, it is run every frame.

(time?: number) => void

tPaperCleanup

An optional cleanup function.

() => void

tPaperScriptReturn

The return value of the function is passed to the script prop.

type tPaperScriptReturn = {
  render: tPaperRenderLoop;
  cleanup: tPaperCleanup;
};

tPaperScript

A function that recieves a HTML canvas and returns a promise that resolves to tPaperScriptReturn (your render loop).

(canvas?: HTMLCanvasElement) => Promise<tPaperScriptReturn>

tPaperPositionEvent

A function that receives the Intersection observer event's entry object. Use this to have custom behavior when the canvas goes out of and comes into the viewport. This function is called when the canvas enters or leaves the viewport.

(entry: IntersectionObserverEntry) => void;

tPaperErrorEvent

This function is called when an error occurs. It receives the error.

(error: Error) => void;

This module provides TypeScript type definitions.