alisabzevari alisabzevari - 21 days ago 5
React JSX Question

Cannot instantiate a StatelessFunctionalComponent that probably returns null

I have defined a component:

interface Role {
name: string;
description: string;
}

interface BPRolesProps extends React.Props<null> {
roles: Role[];
}

const BPRoles = ({ roles }: BPRolesProps) => {
if (!roles.length) {
return null;
}
return (
<div>
{roles.map(r => <div key={r.name}><span title={r.description}>{r.name}</span></div>)}
</div>
);
};


Then I try to render it using render:

render(<BPRoles />, null);


The problem is that I get this error:

error TS2605: JSX element type 'Element | null' is not a constructor function for JSX elements.
Type 'null' is not assignable to type 'ElementClass'.

Answer

There is an issue related to this problem here.

For now, this trick can be used as a workaround:

const BPRoles = ({ roles }: BPRolesProps) => {
  if (!roles.length) {
    return null!; // <= never is assignable to anything, so the return type will be Element
  }
  return (
    <div>
      {roles.map(r => <div key={r.name}><span title={r.description}>{r.name}</span></div>)}
    </div>
  );
};