Search code examples
reactjstypescriptgltfreact-three-fiberreact-three-drei

How to correctly convert jsx to tsx


How to correctly convert exited jsx file from npx gltfjsx command to TypeScript file? Couldn't correct the errors.

import React, {useRef} from 'react'
import { useGLTF } from '@react-three/drei'

export default function Crown(state: any, { ...props }) {
    const group = useRef()
    // @ts-ignore
    const { nodes, materials } = useGLTF('/crown.glb') //TS2339: Property 'materials' does not exist on type 'GLTF'.
    return (
        <group
            // @ts-ignore
            ref={group} //TS2322: Type 'MutableRefObject<undefined>' is not assignable to type 'Ref<Group> | undefined'.   Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<Group>'.     Types of property 'current' are incompatible.       Type 'undefined' is not assignable to type 'Group | null'.
            {...props}
            dispose={null}
        >
            <mesh..../>
            <mesh..../>
            <mesh..../>
            <mesh..../>
        </group>
    )
}

useGLTF.preload('/crown.glb')

Solution

  • The gltfjsx module has a types flag available so you don't have to do it manually.

    Whenever I want to convert a .glb to .tsx, I simply do npx gltfjsx file.glb -t or npx gltfjsx file.glb --types

    Sometimes this gives an error for the ref, if you don't need ref you can delete it, if you do my workaround has been defining the ref type:

     <group
          ref={group as Ref<THREE.Group>}
          {...props}
          dispose={null}
        >
    ...
    </group>