# react-three-fiber
**Repository Path**: mc_gao/react-three-fiber
## Basic Information
- **Project Name**: react-three-fiber
- **Description**: ☘️ React renderer for Threejs (web and react-native)
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2020-07-07
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
These demos are real, you can click them! They contain the full code, too.
npm install three react-three-fiber
#### What is it?
This is a React renderer for Threejs on the web and react-native. Building a dynamic scene graph becomes so much easier when you can break it up into declarative, re-usable components that react to state changes.
#### Does it have regressions?
This is less of an abstraction and more of a pure reconciler (like react-dom in relation to HTML). It does not target a specific Threejs version nor does it need updates when Threejs alters, adds or removes features. It won't change any specifics or rules. There are zero limitations.
#### Is it slower than raw Threejs?
Rendering performance is up to Threejs and the GPU, react-three-fiber drives a renderloop outside of React without overhead. React is otherwise very efficient in building and updating component-trees, which could allow it to potentially outperform manual apps at scale.
# What it looks like ...
Copy the following into a project to get going. [Here's the same](https://codesandbox.io/s/rrppl0y8l4) running in a code sandbox.
```jsx
import { Canvas, useFrame } from 'react-three-fiber'
function Thing() {
const ref = useRef()
useFrame(() => (ref.current.rotation.x = ref.current.rotation.y += 0.01))
return (
console.log('click')}
onPointerOver={e => console.log('hover')}
onPointerOut={e => console.log('unhover')}>
)
}
```
# Canvas
The `Canvas` object is your portal into Threejs. It renders Threejs elements, _not DOM elements_!
```jsx
// Response for pointer clicks that have missed a target
```
You can give it additional properties like style and className, which will be added to the container (a div) that holds the dom-canvas element.
# Defaults that the canvas component sets up
Canvas will create a _translucent WebGL-renderer_ with the following properties: `antialias, alpha, setClearAlpha(0)`
A default _perspective camera_: `fov: 75, near: 0.1, far: 1000, position.z: 5`
A default _orthographic camera_ if Canvas.orthographic is true: `near: 0.1, far: 1000, position.z: 5`
A default _shadowMap_ if Canvas.shadowMap is true: `type: PCFSoftShadowMap`
A default _scene_ (into which all the JSX is rendered) and a _raycaster_.
A _wrapping container_ with a [resize observer](https://github.com/react-spring/react-use-measure): `scroll: true, debounce: { scroll: 50, resize: 0 }`
You do not have to use any of these objects, look under "receipes" down below if you want to bring your own.
# Objects and properties
You can use [Threejs's entire object catalogue and all properties](https://threejs.org/docs). When in doubt, always consult the docs.
You could lay out an object like this:
```jsx
```
The problem is that all of these properties will always be re-created. Instead, you should define properties declaratively.
```jsx
```
#### Shortcuts (set)
All properties that have a `.set()` method can be given a shortcut. For example [THREE.Color.set](https://threejs.org/docs/index.html#api/en/math/Color.set) can take a color string, hence instead of `color={new THREE.Color('hotpink')}` you can do `color="hotpink"`. Some `set` methods take multiple arguments ([THREE.Vector3.set](https://threejs.org/docs/index.html#api/en/math/Vector3.set)), so you can pass an array `position={[100, 0, 0]}`.
#### Shortcuts and non-Object3D stow-away
Stow away non-Object3D primitives (geometries, materials, etc) into the render tree so that they become managed and reactive. They take the same properties they normally would, constructor arguments are passed with `args`. Using the `attach` property objects bind automatically to their parent and are taken off it once they unmount.
You can nest primitive objects, too, which is good for awaiting async textures and such. You could use React-suspense if you wanted!
```jsx
img && (self.needsUpdate = true)} />
```
Sometimes attaching isn't enough. For example, this code attaches effects to an array called "passes" of the parent `effectComposer`. Note the use of `attachArray` which adds the object to the target array and takes it out on unmount:
```jsx
```
You can also attach to named parent properties using `attachObject={[target, name]}`, which adds the object and takes it out on unmount. The following adds a buffer-attribute to parent.attributes.position.
```jsx
```
#### Piercing into nested properties
If you want to reach into nested attributes (for instance: `mesh.rotation.x`), just use dash-case:
```jsx
```
#### Putting already existing objects into the scene-graph
You can use the `primitive` placeholder for that. You can still give it properties or attach nodes to it.
```jsx
const mesh = new THREE.Mesh()
return
```
#### Using 3rd-party (non THREE namespaced) objects in the scene-graph
The `extend` function extends three-fibers catalogue of known native JSX elements.
```jsx
import { extend } from 'react-three-fiber'
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass'
extend({ EffectComposer, RenderPass })
```
# Events
Threejs objects that implement their own `raycast` method (meshes, lines, etc) can be interacted with by declaring events on the object. We support pointer events ([you need to polyfill them yourself](https://github.com/jquery/PEP)), clicks and wheel-scroll. Events contain the browser event as well as the Threejs event data (object, point, distance, etc).
Additionally there's a special `onUpdate` that is called every time the object gets fresh props, which is good for things like `self => (self.verticesNeedUpdate = true)`.
```jsx
console.log('click')}
onWheel={e => console.log('wheel spins')}
onPointerUp={e => console.log('up')}
onPointerDown={e => console.log('down')}
onPointerOver={e => console.log('over')}
onPointerOut={e => console.log('out')}
onPointerEnter={e => console.log('enter')}
onPointerLeave={e => console.log('leave')}
onPointerMove={e => console.log('move')}
onUpdate={self => console.log('props have been updated')}
/>
```
#### Event data
```jsx
({
...DomEvent // All the original event data
...ThreeEvent // All of Three's intersection data
object: Object3D // The object that was actually hit
eventObject: Object3D // The object that registered the event
unprojectedPoint: Vector3 // Camera-unprojected point
ray: Ray // The ray that was used to strike the object
camera: Camera // The camera that was used in the raycaster
sourceEvent: DomEvent // A reference to the host event
delta: number // Initial-click delta
}) => ...
```
#### Propagation and capturing
```jsx
onPointerDown={e => {
// Only the mesh closest to the camera will be processed
e.stopPropagation()
// You may optionally capture the target
e.target.setPointerCapture(e.pointerId)
}}
onPointerUp={e => {
e.stopPropagation()
// Optionally release capture
e.target.releasePointerCapture(e.pointerId)
}}
```
# Hooks
Hooks can only be used **inside** the Canvas element because they rely on context! You cannot expect something like this to work:
```jsx
function App() {
const { size } = useThree() // This will just crash
return (