Add React Three Fiber To Astro

Ben Lazzeroni

December 3, 2024

-

4 min read

In this post we’ll hook up React Three Fiber with Astro. Astro makes this really smooth with its builtin Island architecture that allows us to render heavy 3D apart from the static html flow. We don’t have to worry about this though because getting R3F to work is actually quite simple.

Start by creating a new Astro project with npm create astro@latest and follow the prompt. Astro Prompt

Since we will be using React Three Fiber we will need Astro’s React integration. Simply go into your newly made project directory and install Astro React with the command npx astro add react and follow the prompt again. Astro React Prompt

Lastly we will add React Three Fiber to the project with npm install three @react-three/fiber.

Great! everything is installed and it’s time to get a threejs canvas on the screen. Since we have some default files already with the Astro install we will use them.

First lets make a new file called Experience.jsx in the src/components directory. In this file we will be setting up the basic blocks needed for rendering. With R3F’s declaritive nature its pretty easy, our Canvas component is going to set up the scene and camera while we add a simple box mesh to it. We will then make it a little more interesting by rotating the box using the useFrame hook to update the boxes rotation on everything rendered frame.

Here is the code for the Experience.jsx file.

import { Canvas, useFrame } from "@react-three/fiber";
import { useRef } from "react";

const Box = () => {
  const ref = useRef();

  useFrame(() => {
    ref.current.rotation.x += 0.002;
    ref.current.rotation.y += 0.002;
  });

  return (
    <>
      <mesh ref={ref}>
        <boxGeometry args={[2, 2, 2]} />
        <meshBasicMaterial color={"red"} />
      </mesh>
    </>
  );
};

export default function Experience({}) {
  return (
    <div>
      <Canvas>
        <Box />
      </Canvas>
    </div>
  );
}

Next go into src/pages/index.astro file and add the Experience component. You will import it at the top of the file and insert it above the Welcome component.

---
import Welcome from "../components/Welcome.astro";
import Layout from "../layouts/Layout.astro";
import Experience from "../components/Experience";

// Welcome to Astro! Wondering what to do next? Check out the Astro documentation at https://docs.astro.build
// Don't want to use any of this? Delete everything in this file, the `assets`, `components`, and `layouts` directories, and start fresh.
---

<Layout>
  <Experience client:load />
  <Welcome />
</Layout>

Thats it!

Go ahead an start up the local server with npm run dev and go to localhost:4321 where you should see a spinning red box at the top of the screen. React Three Fiber canvas on an astro page

Want To Chat?

service@ux-engine.com
Headquartered in Chico, Ca Copyright © 2024 - v1.0.0