React Fiber Mesh Element using useRef hook, 'ref.current' is possibly 'undefined'

219 views Asked by At

Environment
Next JS, TypeScript, React Fiber

Code Snippet

import { useFrame } from '@react-three/fiber'
import React, { useRef, useState } from 'react'

interface PolyhedronCanvasProps {
    position: [number, number, number],
    polyhedron: any
}

const PolyhedronCanvas = ( props: PolyhedronCanvasProps ) => {
    const ref = useRef()     
    const [count, setCount] = useState(0)

    useFrame((_, delta) => {  
        ref.current.rotation.x += delta
        ref.current.rotation.y += 0.5 * delta
    })

    return (
        <mesh 
            position={props.position}
            ref={ref}            
            onPointerDown={() => setCount((count + 1) % 3)}
            geometry={props.polyhedron[count]}
        >
            <meshPhongMaterial color={'lime'} wireframe/>
        </mesh>
    )
}

export default PolyhedronCanvas    
ref.current.rotation.x += delta
ref.current.rotation.y += 0.5 * delta

I could probably run the next js application but I still got TypeScript error on those two lines with 'ref.current' is possibly 'undefined'

Again I could able to run the project but I wanted to remove the TypeScript errors which makes my jsx files red in VS Code.

2

There are 2 answers

7
Ori Drori On BEST ANSWER

Set the type of the ref (see docs):

import { Mesh } from 'three'

const ref = useRef<Mesh>(null)     

Check if ref.current exists before assigning the values:

useFrame((_, delta) => {  
  if(ref.current) {
    ref.current.rotation.x += delta
    ref.current.rotation.y += 0.5 * delta
  }
})
0
Yilmaz On
import { Object3D } from "three";

const ref = useRef();

useFrame((_, delta) => {
    if (ref.current) {
        const object3D = ref.current as Object3D;
        object3D.rotation.x += delta;
        object3D.rotation.y += 0.5 * delta;
    }
});