#Three.JS + Next.js

13 messages · Page 1 of 1 (latest)

tulip pulsar
#

Question, has anyone had any success implementing threejs into nextjs? I know next js does SSR, but i feel like there is definitely a way to use threejs.

#

i got this to work, but for some reason it's adding 2 canvases?

#

my threejs component

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

const ThreeScene = () => {
    const sceneRef = useRef();

    useEffect(() => {
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        const renderer = new THREE.WebGLRenderer();

        renderer.setSize(window.innerWidth, window.innerHeight);
        sceneRef.current.appendChild(renderer.domElement);

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

        scene.add(cube);
        camera.position.z = 5;

        const animate = () => {
            requestAnimationFrame(animate);



            renderer.render(scene, camera);
        };

        animate();
    }, []);

    return <div ref={sceneRef} />;
};

export default ThreeScene;

my index

import css from '../styles/Home.module.css'
import ThreeScene from '../components/ThreeScene';

const Home = () => {
  return (
    <div>
      <h1>My Next.js Three.js App</h1>
      <ThreeScene />
    </div>
  );
};

export default Home;

#

What i've tried, removing the rootlayout

import { Lato } from 'next/font/google'
import '../styles/globals.css'

const lato = Lato({
  subsets: ['latin'],
  variable: '--fontLato',
  style: ['normal', 'italic'],
  weight: ['400', '700']
});

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={`${lato.variable}`}>{children}</body>
    </html>
  )
}

#

but obviously nothing loaded then

#

i removed
sceneRef.current.appendChild(renderer.domElement);
but obviously, only the h1 tag loaded

#

this is from inspect element

#

its like its being loaded twice

#

not "like" its literally being loaded twice

#

if anyone has an idea what is happening let me know

noble linden
#

not sure if related, but for me when working locally, i need to comment out <React.StrictMode> otherwise it loads twice (works for final build tho...)

tulip pulsar
#

hm, good idea, but that didn't happen to work in my case