Create a React Three Fiber application
Step 1: Create React project with Vite
npm create vite@latest
The terminal prompt will be as following:
I'm using Typescript in this case but you can choose Javascript as well!
Step 2: Install npm
cd <project-folder>
npm install
npm run dev
In localhost, the page should look something like this:
Step 3: Install necessary dependencies
- React Three Fiber
npm install three@0.166 @react-three/fiber@8.16
- Drei
npm install @react-three/drei@9.108
Step 4: Clean project
Vite created some default codes, let's clean it.
- Delete all codes in
App.tsx
so that it looks like this:
App.tsx
import './App.css'
function App() {
return (
<>
</>
)
}
export default App
- Remove all styles in
index.css
andApp.css
- In
index.css
, add these stylings:
index.css
html,
body,
#root
{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
Step 5: Let's get started!
- Create a file named
Experience.tsx
- All 3D contents need to be inside Canvas:
Experience.tsx
import { Canvas } from "@react-three/fiber";
export default function Experience() {
return (
<Canvas>
<mesh>
<boxGeometry />
<meshBasicMaterial color={'red'} />
</mesh>
</Canvas>
)
}
- In
App.tsx
, add<Experience />
:
App.tsx
function App() {
return (
<>
<Experience />
</>
)
}
Voila, now we have a cute little red box on the screen:
- Add
OrbitControl
by Drei to be able to control the 3D space:
Experience.tsx
<>
<OrbitControls />
...
</>