Search code examples
reactjstypescriptreact-typescript

Type 'Element[]' is missing the following properties from type 'ReactElement<any, any>': type, props, key


I am getting the following error

TS2786: 'Letters' cannot be used as a JSX component. Its return type 'Element[]' is not a valid JSX element. Type 'Element[]' is missing the following properties from type 'ReactElement<any, any>': type, props, key

which I do not understand

// Letters.tsx
import React from 'react';

const Letters = () => {
    const _renderletters = ():JSX.Element[] => {
        return ["a", "b"].map((letter: string, index:number):JSX.Element => {
            return <p key={index}>{letter}</p>
        })
    }
    return _renderletters()
}

export default Letters;


// UseLetters.tsx
import React from 'react'
import Letters from "./Letters";

const UseLetters = () => {
    return <Letters /> // <- this is highlighted with the error
}

export default UseLetters;

Why is that?


Solution

  • I have been blind. This

    // Letters.tsx
    import React from 'react';
    
    const Letters = () => {
        const _renderletters = ():JSX.Element[] => {
            return ["a", "b"].map((letter: string, index:number):JSX.Element => {
                return <p key={index}>{letter}</p>
            })
        }
        return _renderletters()
    }
    
    export default Letters;
    

    Currently returns an array, which must be wrapped into something, i.e. a Fragment

      return <>{_renderletters()}</>