Type 'Element[]' is not assignable to type 'ReactElement<any>'
Asked Answered
A

1

7

I'm trying to add this simple div to the return block of my .tsx file:

<div id="bizible.reportUser" style="display:none" data-email="[email protected]"/>

I do it the following way:

import React from 'react';
import Radium from 'radium';

import Icon from './Icon';
import Header from './Header';

import Colors from '../colors';

const NoMatch = ({ children, title, icon, kind }) => {
  return ([
    <div style={[styles.base, kind && styles[kind]]}>
      <Icon name={icon} style={[styles.icon]} height="48" width="48" />
      <Header title={title} style={[styles.header]} />
      <p style={[styles.message]}>
        {children}
      </p>
    </div>,
    <div id="bizible.reportUser" style="display:none" data-email="[email protected]"/>
  ]
  );
};

But it returns an Error message and does not compile:

error TS2322: Type '({children, title, icon, kind}: { children: any; title: any; icon: any; kind: any; }) => Element[]' is not assignable to type 'StatelessComponent<Props>'.
  Type 'Element[]' is not assignable to type 'ReactElement<any>'.
    Property 'type' is missing in type 'Element[]'.
Astromancy answered 29/6, 2018 at 19:12 Comment(7)
You are returning an array. Does it work if you just keep the ()? I.e from ([ ... ]) to ().Korfonta
no it doesn't @Tholle. It demands an array, otherwise you get this error: "JSX expressions must have one parent element."Astromancy
That doesn't sound right. E.g. the way stateless components are written here works fine.Korfonta
Last version of Reacts apparently requires the array notation: #48887226Astromancy
Yes, that's a fine way of writing it if you don't want to return just a single element, but you are returning a single div as the topmost element, so there is no need for an array is this case.Korfonta
No, I'm returning two divs. But still, that doesn't fix the issueAstromancy
You're right, I'm blind. Sorry about that. Have you tried wrapping it in a React.Fragment instead of an array?Korfonta
G
8

You can always wrap the return value with <React.Fragment> (or <>). This will solve your problem without adding anything to the DOM.

Gagarin answered 16/7, 2020 at 12:7 Comment(2)
Is this the best / only solution? I have the same issue saying: Type 'boolean' is not assignable to type 'ReactElement' after upgrading to React 18Hoo
@Hoo this is not related... this solution won't fix your problem.Gagarin

© 2022 - 2024 — McMap. All rights reserved.