Home > Net >  react implict return in an onClick
react implict return in an onClick

Time:11-24

So I have been seeing this in the codebase recently. An implicit return from an onClick

<Button onClick={() => history.push('/urlTing') }>
   Ting
</Button>

Is this a big no-no? Or is it better? Any input here would be appreciated. Both appear to provide the desired behavior.

Obviously here is what it looks like without the implicit return.

<Button onClick={() => {
   history.push('/urlTing'); 
}}>
   Ting
</Button>

CodePudding user response:

It does not make a difference. If you don't want the implicit return while keeping the one-line format, use the void keyword:

<Button onClick={() => void history.push('/urlTing') }>
   Ting
</Button>

CodePudding user response:

There is nothing wrong with the implicit return. The onClick event handler's return value does not get used by react. Per the docs https://reactjs.org/docs/handling-events.html

Another difference is that you cannot return false to prevent default behavior in React. You must call preventDefault explicitly.

Therefore, it does not matter what your handler returns, or if it returns anything at all.

CodePudding user response:

Creating a callback on each render inside markup, in itself is not the best practice. Back to the question: the main difference, as you mentioned, is between the return value. I doubt the onClick API from React will ever change. But if in the future there will be some kind of a return value expected - that's where you may get yourself into some troubles if you DO return something.

The rule of thumb: if you are not asked to return something - don't do that.

  • Related