Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript React empty function as defaultProps

I have a Stateless Functional Component with an optional function parameter as property (onClick), I tried to define an empty function as default property to be able to do safely in my component :

 <span onClick={props.onClick} />

But I have the following error : 'Expression expected.'

interface IProps {
  size?: sizeType;
  onClick?: (e:any) => void;
}
const Foo: React.SFC = (props: IProps) => {
  // ...
};
const defaultProps: IProps = {
   size: 'default',
   onClick: () => void <-- Expression expected.
};
Foo = defaultProps;

How can I should do this?

like image 518
Fabrice Avatar asked Nov 22 '17 15:11

Fabrice


2 Answers

You cannot use void in javascript as return value. Instead of void, use null as return value.

onClick: () => null
like image 166
Daniel Derevjanik Avatar answered Sep 17 '22 16:09

Daniel Derevjanik


I think using lodashes noop might be a good option because depending on the number of re-renders the component will have BEFORE the component has access to the prop, it will create that many references to an anonymous function that essentially is a place holder for the function you need. Something like:

import noop from 'lodash/noop';
MyComponent.defaultProps = {
  myfunc: noop,
};

Its a small optimization but also prevents the developer from creating an anonymous function for every default prop declaration that a func is needed in.

like image 43
Scott Stern Avatar answered Sep 20 '22 16:09

Scott Stern