14

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?

2
  • Can you please add the code of IProps to your question? Commented Nov 22, 2017 at 15:39
  • I added the interface Commented Nov 22, 2017 at 15:51

4 Answers 4

34

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

onClick: () => null
Sign up to request clarification or add additional context in comments.

Comments

12

You can use the following:

const defaultProps: IProps = {
   size: 'default',
   onClick: () => void(0)
};

Comments

6

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.

Comments

3

I usually do

MyComponent.defaultProps = {
  someNoop: f => f
}

as something that is short, easy to type, and will just return undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.