user10780967
user10780967

Reputation:

Passing an empty function into a React component

I have a React component; for example:

export class Component1 extends Component<IProps, IState> {

One of the props that it accepts is a function:

export interface IProps {    
    a: number,
    b: number,
    onMouseClick: () => void
}

So, when I use this component, I can do something like this:

<Component1 onMouseClick={() => this.DoStuff()} a={1} b={2} />

But what if I want to pass a null function in, so that the function does nothing on Mouse Click; for example:

<Component1 onMouseClick={() => void} a={1} b={2} />

Typescript moans at me, saying that it expects an expression. I can declare an empty function; like this:

<Component1 onMouseClick={() => function(){}} a={1} b={2} />

Is there a nicer way that declaring an empty function? I'm also a little unclear why I can assign the property onMouseClick to void in the IProps definition, but not when using the component.

Upvotes: 8

Views: 34349

Answers (5)

Yozi
Yozi

Reputation: 12757

The void is an operator in JavaScript and it has to be followed by an expression. So () => void is not valid callback definition. Noop function looks like this () => {} or () => undefined and can be used in jsx like this:

<Component1 onMouseClick={() => {}}  a={1} b={2}/>

But I would rather make `onMouseClick optional, it is much more convenient and obvious for a consumer of the component

interface IProps {    
   a: number,
   b: number,
   onMouseClick?: () => void
}

Upvotes: 8

Gonza
Gonza

Reputation: 107

I think this may be useful taking into account linters

<Component1 onMouseClick={() => void undefined} a={1} b={2} />

Upvotes: 0

r g
r g

Reputation: 3901

you can make it optional

export interface IProps {    
    a: number,
    b: number,
    onMouseClick?: () => void 
}

and probably you want to do default props with default implementation so you won't have to check if onMouseClick is a function every time you use it

class ... extends React.Component<...>{
 static defaultProps = {
  onMouseClick: () => null,
 }
}

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250006

() => void is a type as far as typescript is concerned (and is actually a syntax error in Javascript). You should try () => void 0 which is a function that returns undefined

<Component1 onMouseClick={() => void 0} a={1} b={2} />

Or if you want to allow null or be optional change the type of the prop to include null, although you will need extra checking in the component

export interface IProps {    
    a: number,
    b: number,
    onMouseClick?: () => void // ? makes it optional
}
<Component1 a={1} b={2} /> // no error

Upvotes: 13

dsych
dsych

Reputation: 762

Try

export interface IProps {    
    a: number,
    b: number,
    onMouseClick?: () => void
}

or

export interface IProps {    
    a: number,
    b: number,
    onMouseClick: () => void | null
}

Upvotes: 2

Related Questions