Installation
Learn how to install react-three-fiber
npm install three @react-three/fiber
Fiber is compatible with React v16.8+ and works with ReactDOM and React Native.
Getting started with React Three Fiber is not nearly has hard as you might have thought, but various frameworks may require particular attention. We've put together guides for getting started with each popular framework:
- Create React App
- Next.js
- Expo
If you just want to give it a try, fork this example on codesandbox!
Create React App
create-react-app
will work out of the box, nothing special here!
Next.js
It should work out of the box but you will encounter untranspiled add-ons in the three.js ecosystem, in that case you can install the next-transpile-modules
module:
npm install next-transpile-modules --save-dev
Then, add this to your next.config.js
const withTM = require('next-transpile-modules')(['three'])
module.exports = withTM()
Make sure to check out our official next.js starter, too!
Expo & React Native
This example uses expo-cli
for the sake of simplicity, but you can use your own barebones setup if you wish.
# Install expo-cli, this will create our app
npm install expo-cli -g
# Create app and cd into it
expo init my-app
cd my-app
# Install dependencies
npm install three @react-three/fiber@beta react@beta
# Start
expo start
Just import from native targets and that's it!
import { Canvas } from '@react-three/fiber/native'
import { useGLTF } from '@react-three/drei/native'
Without build tools
You can use React Three Fiber with browser-ready ES Modules from skypack.dev and a JSX-like syntax powered by htm.
import ReactDOM from 'https://cdn.skypack.dev/react-dom'
import React, { useRef, useState } from 'https://cdn.skypack.dev/react'
import { Canvas, useFrame } from 'https://cdn.skypack.dev/@react-three/fiber'
import htm from 'https://cdn.skypack.dev/htm'
const html = htm.bind(React.createElement)
ReactDOM.render(html`<${Canvas}>...<//>`, document.getElementById('root'))
Full example
import ReactDOM from 'https://cdn.skypack.dev/react-dom'
import React, { useRef, useState } from 'https://cdn.skypack.dev/react'
import { Canvas, useFrame } from 'https://cdn.skypack.dev/@react-three/fiber'
import htm from 'https://cdn.skypack.dev/htm'
const html = htm.bind(React.createElement)
function Box(props) {
const mesh = useRef()
const [hovered, setHover] = useState(false)
const [active, setActive] = useState(false)
useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01))
return html` <mesh
...${props}
ref=${mesh}
scale=${active ? 1.5 : 1}
onClick=${() => setActive(!active)}
onPointerOver=${() => setHover(true)}
onPointerOut=${() => setHover(false)}
>
<boxGeometry args=${[1, 1, 1]} />
<meshStandardMaterial color=${hovered ? 'hotpink' : 'orange'} />
</mesh>`
}
ReactDOM.render(
html` <${Canvas}>
<ambientLight />
<pointLight position=${[10, 10, 10]} />
<${Box} position=${[-1.2, 0, 0]} />
<${Box} position=${[1.2, 0, 0]} />
<//>`,
document.getElementById('root')
)