Shlomi Zadok
Shlomi Zadok

Reputation: 278

three.js OBJLoader not loading in react

I am trying to load an object (.obj) file to use with three.js and react (with react-three-renderer), yet get an My code looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import React3 from 'react-three-renderer';
import TrackballControls from './TrackballControls';
import * as THREE from 'three';
import * as OBJLoader from 'three-obj-loader';
OBJLoader(THREE);

class MyClass extends React.Component {
...
  render() {
    ...
    const objLoader = new THREE.OBJLoader();
  }
}

However, I keep on getting: "export 'OBJLoader' (imported as 'THREE') was not found in 'three' Anyone with an idea?

Upvotes: 7

Views: 6408

Answers (3)

Hitesh Sahu
Hitesh Sahu

Reputation: 45052

Update 2019 use "three-obj-mtl-loader" instead of 'three-obj-loader'

  import { MTLLoader, OBJLoader } from "three-obj-mtl-loader";

Use this method to load material and OBJ model

   /**
   * Load and Display OBJ Model
   */
  loadObjModel = (materialURL, objectURL) => {
    new MTLLoader().load(materialURL, materials => {
      materials.preload();
      //materials.Material.side = THREE.DoubleSide;
      console.log("Loaded Materials");
      var objLoader = new OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(
        objectURL,
        object => {
          //const root = object.detail.loaderRootNode;
          console.log("Loaded Obj" + object);
          let mesh = object;
          this.scene.add(object);
          mesh.position.set(0, 0, 0);
          mesh.scale.set(0.07, 0.07, 0.07);
        },
        xhr => {
          console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
        },
        // called when loading has errors
        error => {
          console.log("An error happened" + error);
        }
      );
    });
  };

Load obj models with material like this

this.loadObjModel("./assets/windmill-fixed.mtl", "./assets/windmill.obj");

Upvotes: 0

GrJay
GrJay

Reputation: 21

OBJLoader is now part of the core three.js library, so you can access it simply by doing:

 const objLoader = new THREE.OBJLoader();

While removing the lines:

import * as OBJLoader from 'three-obj-loader';
OBJLoader(THREE);

Since you have already imported the three.js library in your code.

Upvotes: 1

Shlomi Zadok
Shlomi Zadok

Reputation: 278

So it seems that adding this.THREE = THREE to the react component does the trick (weird, eh?). So my code currently looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import React3 from 'react-three-renderer';
import TrackballControls from './TrackballControls';
import * as THREE from 'three';
import * as OBJLoader from 'three-obj-loader';
OBJLoader(THREE);

class MyClass extends React.Component {
...
  render() {
    ...
    this.THREE = THREE;
    const objLoader = new this.THREE.OBJLoader();
  }
}

Upvotes: 8

Related Questions