Mateus Arruda
Mateus Arruda

Reputation: 305

Can't import a 3D model using ThreeJS and React

I'm using React and ThreeJS to import a 3D model into a web page. The problem is in the function to load the mesh into my ThreeJS scene. I'm getting the following error:

TypeError: Cannot read property 'scene' of undefined

Right befor the line I add the mesh into the scene I print out the same object and there is a property 'scene' inside my GLB file. Here is an image:

enter image description here

Here is my code:

import React, { Component } from 'react'
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import gltfPath from '/home/mateus/Documents/index/src/cube.glb'


class ThreeDViewer extends Component {
    componentDidMount() {
        const width = this.mount.clientWidth
        const height = this.mount.clientHeight

        this.scene = new THREE.Scene()

        this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 5000)
        this.camera.position.z = 20

        this.renderer = new THREE.WebGLRenderer()
        this.renderer.setSize(width, height)
        this.mount.appendChild(this.renderer.domElement)

        const geometry = new THREE.BoxGeometry(1, 1, 1)
        const material = new THREE.MeshBasicMaterial({ color: '#00ff00' })

        this.cube = new THREE.Mesh(geometry, material)

        this.light = new THREE.AmbientLight(0xffffff, 100)
        this.scene.add(this.light)

        this.loader = new GLTFLoader()
        this.loader.load(gltfPath, function (gltf) {
            // I print gltf but I can't add it to my scene I don't know why
            console.log(gltf)
            this.scene.add(gltf.scene.children[2])

        }, undefined, function (error) {
            console.error(error)
        })


        this.start()
    }

If I add the cube from the ThreeJs lib it works fine, but with my custom model it doesn't work. THe model is just a simple cube exported as glb by blender 2.81.

Upvotes: 2

Views: 1848

Answers (1)

helloitsjoe
helloitsjoe

Reputation: 6529

this is undefined in your callback, try using an arrow function instead of a function declaration:

this.loader.load(gltfPath, (gltf) => {
  this.scene.add(gltf.scene.children[2]);
});

Upvotes: 2

Related Questions