Home > Back-end >  'ReactNode' is not a valid JSX element
'ReactNode' is not a valid JSX element

Time:05-27

I have the following piece of code (codesandbox):

import { ComponentType, ReactNode } from "react";

type DatetimeCell = ({ value }: { value: string }) => ReactNode;

function getDateTimeCell(): DatetimeCell {
  return ({ value }) => value;
}

function buildCell({
  value
}: {
  value: string;
}): ComponentType<{ value: string }> {
  const DateTimeCell = getDateTimeCell();
  return ({ value }) => <DateTimeCell value={value} />;
}

When returning in buildCell I get the error:

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

I thought ReactNode would be the most general type for valid JSX, but it seems like that is not the case.
Why is ReactNode not valid JSX and how can I solve this issue?

CodePudding user response:

Part of ReactNode type is undefined, which is not a valid JSX element I think.

The easiest way to solve the problem would be just to type DatetimeCell as Component as well, and always return an element from getDateTimeCell - just wrap the result in a fragment.

import React, { ComponentType } from 'react';

type DatetimeCell = ComponentType<{ value: string }>;

function getDateTimeCell(): DatetimeCell {
  return ({ value }) => <>{value}</>;
}

function buildCell({ value }: { value: string }): ComponentType<{ value: string }> {
  const DateTimeCell = getDateTimeCell();
  return ({ value }) => <DateTimeCell value={value} />;
}

CodePudding user response:

When you invoke DateTimeCell it expects a JSX element (ReactNode) to be returned. You are currently returning a string and not a React node in your getTimeCell function. I recommend typing your functional components using the FC type provided by react as below:

import { FC } from "react";

type Props = { value: string };
type DatetimeCell = FC<Props>;

function getDateTimeCell(): DatetimeCell {
  return ({ value }) => <>{value}</>;
}

function buildCell({ value }: Props): DatetimeCell {
  const DateTimeCell = getDateTimeCell();
  return ({ value }) => <DateTimeCell value={value} />;
}

buildCell({ value: "hello" });
  • Related