Home > Software engineering >  Type 'undefined' is not assignable to type 'Element | null'
Type 'undefined' is not assignable to type 'Element | null'

Time:01-06

I use a component :

const data: any[] = []

<Tiers data={data}/>

My component is built like this:

const Tiers = ({
   data,
   }: {
    data?: any;
}) => {

    console.log('data', data?.length!);
    if(!data.length) return undefined;

};

export default Tiers;

I get the following message automatically :

'Tiers' cannot be used as a JSX component.
  Its return type 'undefined' is not a valid JSX element.

CodePudding user response:

Use

return null

instead of

return undefined

to make Tiers a valid JSX component.

You need two return statements in the component like below:

const Tiers = ({
   data,
   }: {
    data?: any;
}) => {

    console.log('data', data?.length!);
    if(!data.length) return null;
    return null
};

export default Tiers;

CodePudding user response:

Your code has two problems,

  1. It needs at least one condition that returns a JSX.Element(even a very simple one like Hello), if not, you probably needed a function instead.
  2. A component cannot return undefined. If you want it to return nothing, you should return null instead of undefined.
  • Related