Home > Blockchain >  Type 'ComponentType<{}> | ReactNode' is not assignable to type 'ReactNode'
Type 'ComponentType<{}> | ReactNode' is not assignable to type 'ReactNode'

Time:12-13

I cannot figure out what is the error. I have already looked over here and none of them seem to work.

App

import React from "react";
import Cell from "./components/cell/Cell";

function App() {
  return <Cell>Hello</Cell>;
}

export default App;

Cell Component

import React, { FunctionComponent, useState } from "react";
import classes from "./Cell.module.css";

export type CellProps = {
  children: React.ComponentType | string;
};

const Cell: FunctionComponent<CellProps> = (props) => {
  const [isEditMode, setIsEditMode] = useState(false);

  const changeLabelToInput = () => {
    setIsEditMode(true);
  };

  return isEditMode ? (
    <input />
  ) : (
    <div onClick={changeLabelToInput}>{props.children}</div>
  );
};

export default Cell;

If I run this I get the next error: TS2322: Type 'ComponentType<{}> | ReactNode' is not assignable to type 'ReactNode'.

CodePudding user response:

Just change the type of the children in your interface:

import React, { FunctionComponent, useState } from "react";
import classes from "./Cell.module.css";

export type CellProps = {
  children: React.ReactNode;
};

const Cell: FunctionComponent<CellProps> = (props) => {
  const [isEditMode, setIsEditMode] = useState(false);

  const changeLabelToInput = () => {
    setIsEditMode(true);
  };

  return isEditMode ? (
    <input />
  ) : (
    <div onClick={changeLabelToInput}>{props.children}</div>
  );
};

export default Cell;

Because React.ReactNode contains different types:

type React.ReactNode = string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | React.ReactFragment | React.ReactPortal | null | undefined
  • Related