javascriptreactjsgltfthreejs-editor

load a 3D model with GLTFLoader (ThreeJS) in Reactjs without using React Fiber


I want to load a 3D model with GLTFLoader but it gives me a syntax error

and I tried these ways

but all of the above didn't work with me

How can I solve this without using React Fiber?

enter image description here

import { useEffect } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import Stats from "three/examples/jsm/libs/stats.module";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";

export default function Main() {
  useEffect(() => {
    /**
     * scene
     */
    const scene = new THREE.Scene();

    /**
     * textures
     */
    const textureLoader = new THREE.TextureLoader();
    const matcapTexture = textureLoader.load("./static/textures/matcaps/1.png");

    /**
     * objects
     */

    // torus
    const torusGeometry = new THREE.TorusBufferGeometry(0.2, 0.1, 15, 45);
    // const torusMaterial = new THREE.MeshMatcapMaterial({ map: matcapTexture });
    const torusMaterial = new THREE.MeshNormalMaterial();
    const torus = new THREE.Mesh(torusGeometry, torusMaterial);
    torus.position.set(0, 0.3, 0);
    scene.add(torus);

    // 3D model
    const loader = new GLTFLoader();

    loader.load("./model_1/scene.gltf", (gltf) => {
      scene.add(gltf.scene);
    });

    /**
     * camera
     */
    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.01,
      10000
    );
    camera.position.set(0, 0, 4);
    scene.add(camera);

 /**
 * renderer
 */
const canvas = document.querySelector("#canvasElement");
const renderer = new THREE.WebGLRenderer({
  canvas,
  antialias: true,
});
renderer.setSize(window.innerWidth, 400);
renderer.setClearColor("white");
  }, []);
}

Solution

  • Storing it in public folder is not a solution. What if you are getting 3D model from server? The issue is that your react component rendered before getting gltf load. So you need to load it before render. So the easy and Quick solution is to use useGLTF hook. https://github.com/pmndrs/drei#usegltf