Next.js is a powerful React framework that allows for server-side rendering and static site generation, among other features. Three.js is a popular library for creating 3D graphics in the browser. Combining these two technologies allows you to build robust, performance-optimized 3D applications. In this article, we’ll walk through setting up a basic Next.js project and integrating Three.js to render a 3D scene.

Setting Up Your Next.js Project

First, let’s create a new Next.js project. Open your terminal and run the following commands:

npx create-next-app@latest my-threejs-app
cd my-threejs-app
npm install three

This will create a new Next.js project in the my-threejs-app directory and install Three.js.

Creating a 3D Scene with Three.js

Next, let’s create a simple 3D scene. We’ll create a new component that initializes a Three.js scene and renders it.

Create the Three.js component

Create a new file components/ThreeScene.js and add the following code:

import { useEffect, useRef } from 'react';
import * as THREE from 'three';

const ThreeScene = () => {
  const mountRef = useRef(null);

  useEffect(() => {
    const mount = mountRef.current;

    // Scene
    const scene = new THREE.Scene();

    // Camera
    const camera = new THREE.PerspectiveCamera(
      75,
      mount.clientWidth / mount.clientHeight,
      0.1,
      1000
    );
    camera.position.z = 5;

    // Renderer
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(mount.clientWidth, mount.clientHeight);
    mount.appendChild(renderer.domElement);

    // Add a cube
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    // Animation loop
    const animate = () => {
      requestAnimationFrame(animate);

      cube.rotation.x += 0.01;
      cube.rotation.y += 0.01;

      renderer.render(scene, camera);
    };

    animate();

    // Clean up
    return () => {
      mount.removeChild(renderer.domElement);
    };
  }, []);

  return <div ref={mountRef} style={{ width: '100%', height: '100vh' }} />;
};

export default ThreeScene;

In this component:

  • We use a useRef hook to create a reference to the DOM element where the Three.js scene will be mounted.
  • Inside a useEffect hook, we initialize the Three.js scene, camera, and renderer.
  • We create a simple cube and add it to the scene.
  • We set up an animation loop to rotate the cube and render the scene.
  • We clean up the renderer when the component is unmounted.

Use the ThreeScene component

Open the pages/index.js file and update it to use the ThreeScene component:

import Head from 'next/head';
import ThreeScene from '../components/ThreeScene';

export default function Home() {
  return (
    <div>
      <Head>
        <title>Three.js with Next.js</title>
        <meta name="description" content="Three.js with Next.js example" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main style={{ height: '100vh', margin: 0 }}>
        <ThreeScene />
      </main>
    </div>
  );
}

Running Your Next.js Application

Now, you can run your Next.js application:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see a rotating green cube rendered by Three.js.

Conclusion

Integrating Three.js with Next.js allows you to create powerful, server-rendered 3D applications. This tutorial covered the basics of setting up a Next.js project and integrating a simple Three.js scene. From here, you can explore more advanced features of Three.js and build complex 3D applications.

For more updates on programming trends and tutorials, visit blogsea.net regularly.

Integrating Three.js with Next.js – FAQs

What is Three.js?

Three.js is a JavaScript library for creating 3D graphics in the browser.

How do you install Three.js in a Next.js project?

Run npm install three in your Next.js project directory.

What does the useRef hook do in the ThreeScene component?

useRef creates a reference to the DOM element where the Three.js scene will be mounted.

Why is useEffect used in the ThreeScene component?

useEffect initializes the Three.js scene, camera, and renderer, and sets up the animation loop when the component mounts.

How is the size of the renderer set in the ThreeScene component?

The renderer size is set to the client width and height of the mount element.

Newsletter

I am a Software developer

My name is muhammad adnan and i am a professtional software developer. specialize in designing and developing efficient software applications.

Check out My Portfolio