alisabzevari
alisabzevari

Reputation: 8126

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'.

Upvotes: 2

Views: 124

Answers (2)

alisabzevari
alisabzevari

Reputation: 8126

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>
  );
};

Upvotes: 1

finalfreq
finalfreq

Reputation: 6980

Stateless pure function components cannot be rendered this way instead you would need a container component that is built using standard React.createClass or using the es6 version and it would render your stateless component and be what is used for the ReactDOM.render method. see https://github.com/facebook/react/issues/5455

also ReactDOM.render expects a dom element as the second argument. render(<BPRoles />, null); you need a valid html element as the second argument, you are passing null which React knows isn't a DOM element.

Upvotes: 0

Related Questions