skip to Main Content

The following code (taken from the reactjs-popup documentation) is giving the Typescript error Type '(close: any) => Element' is not assignable to type 'ReactNode'.ts(2322) when using the reactjs-popup component. Other than using a "@ts-ignore" is there a way to address this error?

import React from 'react';
import Popup from 'reactjs-popup';

const mypopup = () => (
  <div>
    <Popup
      trigger={<button>Information</button>}
      modal
    >
      {close => (
        <div>
          <div>What is this?</div>
          <button onClick={() => { close(); }}>close</button>
        </div>
      )
      }
    </Popup>
  </div>
);

2

Answers


  1. Try the following:

    import React from 'react';
    import Popup from 'reactjs-popup';
    
    const PopupContent: React.FC<{ close: () => void }> = ({ close }) => (
      <div>
        <div>What is this?</div>
        <button onClick={close}>close</button>
      </div>
    );
    
    const MyPopup: React.FC = () => (
      <div>
        <Popup
          trigger={<button>Information</button>}
          modal
        >
          {close => <PopupContent close={close} />}
        </Popup>
      </div>
    );
    
    export default MyPopup;
    

    Define the children as a functional component PopupContent separately and use it within the Popup component:

    Login or Signup to reply.
  2. Congrats, you encountered a problem that is not your fault! This is an oversight in the types for the reactjs-popup package.

    You are defining the child of the Popup as a function. This is supported by the library and included in their docs, which show the use of the "function as children pattern".

    But when you look at their TypeScript types, this sort of use is not covered. The children property of the Popup is defined as:

      children: React.ReactNode;
    
      //| ((close: () => void, isOpen: boolean) => React.ReactNode);
    

    The type that you need is there in their source code, but it’s commented out?! Very strange. As it stands, the types say that the children of the Popup can only be a ReactNode and cannot be a function.

    You should open an issue in their repo to report this mistake. They have a big banner that the package is looking for maintainers so I would not expect it to get fixed anytime soon.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search