Search code examples
reactjsfluent-ui

React/Typescript restrictions on onRenderCell/onClick/... functions?


I'm trying to run Fluent UI Basic List example on my own bench. The example is presented here: https://developer.microsoft.com/en-us/fluentui#/controls/web/list. I copied entire example's code to app and replaced example's data with my own array. However I'm getting following error:

Type '(item: IExampleItem, index: number | undefined) => JSX.Element' is not assignable to type 
'(item?: { key: number; name: string; } | undefined, index?: number | undefined, isScrolling?: 
boolean | undefined) => ReactNode'.`
Types of parameters 'item' and 'item' are incompatible.
Type '{ key: number; name: string; } | undefined' is not assignable to type 'IExampleItem'.
  Type 'undefined' is not assignable to type 'IExampleItem'.  TS2322

83 | 
84 | 
85 |       <List items={data} onRenderCell={onRenderCell} />
   |                          ^
86 | 
87 |   );
88 | };

Is it because this is a Typescript file? Should I disable something to change compilation and prevent such errors?

My code after changes looks as follows: https://codepen.io/vipperdev/pen/QWNdeJe


Solution

  • So, from the documentation:

    onRenderCell

    (item?: T, index?: number, isScrolling?: boolean) => React.ReactNode

    Method to call when trying to render an item.

    Notice the question mark next to the item? It signifies item is optional, so it may or may not be there, right? You have to handle that in your function as well in terms of type of the parameter. For example,

    const onRenderCell = (
      item: IExampleItem | undefined,
      index: number | undefined
    ): JSX.Element => {
      return (
        <div className={classNames.itemCell} data-is-focusable={true}>
          {item?.name}
        </div>
      );
    };
    

    I made two changes above:

    • item: IExampleItem is now item: IExampleItem | undefined.
    • {item?.name} instead of {item.name} to tackle the possibility of item being undefined.

    Here's a working codesandbox without the typescript error.

    Let me know if you have any questions!