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="some@email.com"/>

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="some@email.com"/>
  ]
  );
};

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[]'.
ntonnelier
  • 1,539
  • 3
  • 23
  • 49
  • You are returning an array. Does it work if you just keep the `()`? I.e from `([ ... ])` to `()`. – Tholle Jun 29 '18 at 19:30
  • no it doesn't @Tholle. It demands an array, otherwise you get this error: "JSX expressions must have one parent element." – ntonnelier Jun 29 '18 at 19:37
  • That doesn't sound right. E.g. [the way stateless components are written here](https://www.typescriptlang.org/docs/handbook/react-&-webpack.html#write-some-code) works fine. – Tholle Jun 29 '18 at 19:41
  • Last version of Reacts apparently requires the array notation: https://stackoverflow.com/questions/48886726/react-expressions-must-have-one-parent-element – ntonnelier Jun 29 '18 at 19:46
  • 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. – Tholle Jun 29 '18 at 19:52
  • 1
    No, I'm returning two divs. But still, that doesn't fix the issue – ntonnelier Jun 29 '18 at 20:05
  • You're right, I'm blind. Sorry about that. Have you tried wrapping it in a [React.Fragment](https://reactjs.org/docs/fragments.html) instead of an array? – Tholle Jun 29 '18 at 20:13

1 Answers1

8

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

isherwood
  • 58,414
  • 16
  • 114
  • 157
Guy Engel
  • 2,436
  • 1
  • 17
  • 13
  • Is this the best / only solution? I have the same issue saying: `Type 'boolean' is not assignable to type 'ReactElement'` after upgrading to React 18 – Tobiq Sep 18 '22 at 03:42
  • @Tobiq this is not related... this solution won't fix your problem. – Guy Engel Oct 30 '22 at 12:56