React Fiber Mesh Element employs the useRef hook, causing 'ref.current' to potentially be 'undefined'

Web Development Tools
Exploring Next JS, TypeScript, and React Fiber

Sample Code

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

While attempting to launch the Next JS application, encountered some TypeScript errors related to

'ref.current' is possibly 'undefined'
in the specified lines.

Although the project is functional, striving to resolve these TypeScript errors causing inconsistencies in the appearance of JSX files within VS Code.

Answer №1

Ensure to specify the type of the ref variable according to the documentation available at this link:

import { Mesh } from 'three'

const ref = useRef<Mesh>(null)     

Always verify if the ref.current property exists before manipulating its values:

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

Answer №2

import { Object3D } from "three";

const reference = useRef();

useFrame((_, deltaTime) => {
    if (reference.current) {
        const obj3D = reference.current as Object3D;
        obj3D.rotation.x += deltaTime;
        obj3D.rotation.y += 0.5 * deltaTime;
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

Modify the value during the oninput event in TypeScript

I am trying to dynamically change a span element based on the input value when the event 'input' is triggered. Below is my HTML code: <div class="slidecontainer"> <input type="range" min="1" max="1000" value="50" class="slider" id= ...

The JSON.stringify method in TypeScript/JavaScript does not align with the json-String parameter or request body in a Java controller

Currently, I am utilizing jdk 1.8 and have a rest endpoint in my Java controller: @PostMapping("/filters") public ResponseEntity<StatsDTO> listWithFilter( @RequestBody(required = false) String filter ) { try { ............... } } A test sn ...

The attribute 'value' is not present in the object of type 'Readonly<{}>'

My current project involves creating a form that will dynamically display content based on the response from an API. The code I am working with is structured as follows: class Application extends React.Component { constructor(props) { super(props); ...

Issue with ReactTS Route Triggering Invalid Hook Call

My implementation of the PrivateRoute component is as follows: interface Props { path: string, exact: boolean, component: React.FC<any>; } const PrivateRoute: React.FC<Props> = ({ component, path, exact }) => { return ( ...

What is the best way to send a ref from forwardRef to a specialized hook in TypeScript?

I'm currently working on implementing the useIntersection hook in my code. Everything seems to be functioning correctly, but I've run into some issues with TypeScript: import { MutableRefObject, useEffect } from 'react'; export default ...

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

Request NPM to fetch the complete TypeScript source code, not limited to just the *.d.ts files

Is there a way to request NPM to fetch the TypeScript source files of dependencies, rather than just the *.d.ts and compiled *.js files? I rely on VS Code's Go To Definition feature, but when it comes to dependencies, it only directs me to .d.ts file ...

Having trouble showing JSON data with Ionic 2 and Xcode?

Extracting JSON data from a JSON file in my project and viewing it using "ionic serve" on my Mac has been successful. However, I am facing an issue after building for IOS in XCode. I import the generated project into XCode as usual, but the JSON data is no ...

Indicate a specific type for the Express response

Is there a method to define a specific type for the request object in Express? I was hoping to customize the request object with my own type. One approach I considered was extending the router type to achieve this. Alternatively, is there a way to refactor ...

I am facing an issue where the conversations entered by the user and those generated by the AI are not being stored in my Postgres database within my next.js application

Whenever a question is posed to the AI and a response is provided, the issue arises where the information is not getting saved in the database. Despite including console.log statements in the route.ts file indicating that messages from both the AI and th ...

Tips for streamlining IF statements with multiple conditions

When looking at various code samples, I often see something like this: if(X == x && A == a){ } else if (X == y && A == b){ } else if (X == z && A == c){ } else if (X == zz && A == d){ } Alternatively, there are conditions ...

Having trouble retrieving information from Firebase's Realtime Database

I am currently working on developing a QR Code Scanner using Ionic and Firebase. I have encountered an issue where the app displays a Product not found toast message when I scan a QR Code to match the PLU with the information stored in Firebase. Unfortunat ...

Getting the mouse location with three.js: A step-by-step guide

Hey there, I'm currently working with IcosahedronGeometry. I've added CircleGeometry to each of its vertices. My goal now is to allow the circle to sense the mouse movement and follow it when it gets close. To achieve this, I've created a Ri ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

Creating a barrier between objects in motion

I need assistance with creating a connection between two dynamic vertices in my project. The information for each vertex is stored within an object named object, containing the position data as a THREE.Vector3. To create the line connecting these vertices ...

Tools for diagnosing WebGL Three.js issues

Yesterday, I posed a question and now I want to take a different approach while still keeping the previous discussion going. (The initial question was about variable frame rates in Three.js.) Instead of directly addressing that question, I'm curious ...

Utilizing category-based data filtering in a React functional component

This is my first venture into ecommerce projects using React.js. I've set up a product listing with categories displayed on the left side, as shown in the screenshot below. The goal is to filter products based on category. I'm almost there, bu ...

Tips for incorporating null checks into a function in TypeScript

In my code, I have multiple functions that require a null check on an object before proceeding with certain actions or throwing an error if the object is null. Here is an example of what it looks like: interface SomeObject { doThingOne: () => string ...