Reputation: 1089
WARNING This is not a copy of three.js OBJLoader not loading in react. react-three-renderer is deprecated and I use functional components here.
I need to load an .obj
file but two problems appear. First, it throws TypeError: instance is undefined
by react-three-fiber. Second, it loads .obj
as HTML: Error: THREE.OBJLoader: Unexpected line: "<!DOCTYPE html>"
.
Are these issues related to Parcel, THREE or react-three-fiber?
Here's the code that doesn't work:
App.js
import React from 'react'
import { render } from 'react-dom'
import { Canvas } from 'react-three-fiber'
import Model from '/Model'
import Controls from '/Controls'
import '/style.css'
const App = () => {
return (
<main>
<Canvas>
<Model url="demo.obj" />
<Controls />
</Canvas>
</main>
)
}
render(<App />, document.getElementById('app'))
Controls.js
import React, { useRef } from 'react'
import { useThree, useRender, extend } from 'react-three-fiber'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
extend({ OrbitControls })
const Controls = props => {
const { camera } = useThree()
const controls = useRef()
useRender(({ camera }) => {
controls.current && controls.current.update()
camera.updateMatrixWorld()
})
return <orbitControls ref={controls} args={[camera]} {...props} />
}
export default Controls
Model.js
import React, { useRef, useMemo } from 'react'
import { Math as THREEMath } from 'three'
import { useRender } from 'react-three-fiber'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'
const Model = ({ url }) => {
const model = useRef()
let rot = 0
const obj = useMemo(() => new OBJLoader().load(url), [url])
useRender(() => {
const rad = 5 * Math.sin(THREEMath.degToRad(rot += 0.3))
model.current.rotation.set(rad, rad, 0)
})
return <primitive object={obj} ref={model} />
}
export default Model
Upvotes: 2
Views: 4237
Reputation: 1435
wrong path. the doctype stuff is the 404 page it pulls. as of r3f 3 you can use the useLoader hook, it makes error handling easier since it's based on react suspense, so you could wrap it into error boundaries and fallbacks.
Upvotes: 1