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?
You cannot use void
in javascript as return value. Instead of void, use null
as return value.
onClick: () => null
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With