Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading