Reputation: 365
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?
Upvotes: 14
Views: 21775
Reputation: 74
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.
Upvotes: 6
Reputation: 15372
I usually do
MyComponent.defaultProps = {
someNoop: f => f
}
as something that is short, easy to type, and will just return undefined
.
Upvotes: 3
Reputation: 24941
You can use the following:
const defaultProps: IProps = {
size: 'default',
onClick: () => void(0)
};
Upvotes: 12
Reputation: 340
You cannot use void
in javascript as return value. Instead of void, use null
as return value.
onClick: () => null
Upvotes: 34