Defgun
Defgun

Reputation: 79

Object cannot be used as JSX component

I'm getting the error from Typescript that GroundLoadTextures can't be used as a JSX component. My goal is to set up a textureloadercomponent for a react-three-fiber-scene, so I can use the loaded textures in other components.

'GroundLoadTextures' cannot be used as a JSX component. Its return type '{ colorMap: Texture; displacementMap: Texture; normalMap: Texture; roughnessMap: Texture; aoMap: Texture; }' is not a valid JSX element. Type '{ colorMap: Texture; displacementMap: Texture; normalMap: Texture; roughnessMap: Texture; aoMap: Texture; }' is missing the following properties from type 'Element': type, props, key

import { useTexture } from "@react-three/drei";

function GroundLoadTextures() {
    const [colorMap, displacementMap, normalMap, roughnessMap, aoMap] = useTexture([
        '/textures/stoneFloor/color.jpg',
        '/textures/stoneFloor/displacement.png',
        '/textures/stoneFloor/normal.jpg',
        '/textures/stoneFloor/roughness.jpg',
        '/textures/stoneFloor/ao.jpg'
    ])
    const groundTextures = {
        colorMap: colorMap,
        displacementMap: displacementMap,
        normalMap: normalMap,
        roughnessMap: roughnessMap,
        aoMap: aoMap
    }
    return(
        groundTextures
    )
}

export default function LoadTextures() {
    return(
        <GroundLoadTextures />
    )
  }

Upvotes: 0

Views: 571

Answers (2)

Shyam
Shyam

Reputation: 5497

You can't return a Object from the a React Component . You should always return an JSX element from a react component .

In your case what you need is a custom hook .

import { useTexture } from "@react-three/drei";

function useGroundLoadTextures() {
const [colorMap, displacementMap, normalMap, roughnessMap, aoMap] = useTexture([
    '/textures/stoneFloor/color.jpg',
    '/textures/stoneFloor/displacement.png',
    '/textures/stoneFloor/normal.jpg',
    '/textures/stoneFloor/roughness.jpg',
    '/textures/stoneFloor/ao.jpg'
])
const groundTextures = {
    colorMap: colorMap,
    displacementMap: displacementMap,
    normalMap: normalMap,
    roughnessMap: roughnessMap,
    aoMap: aoMap
}

return groundTextures;
}

export default usegroundLoadTextures; 

With this custom hook inplace now you can import this in other places and use it.

import useGroundLoadTextures from './..'

function SomeOtherComponent(){
  const groundTextures = useGroundLoadTextures();
  ....
}

Upvotes: 2

amdev
amdev

Reputation: 7442

you are returning an object literal from your GroundLoadTextures function and you are trying to render it in react. this will not be going to work!

react component could not return anything thing else rather than array or jsx element.

if you want to use those values in other places like LoadTextures you might use its values (maybe like destructuring them).

Upvotes: 1

Related Questions