Alex Povar
Alex Povar

Reputation: 4960

Is it safe to pass undefined in React's onClick?

Is it safe to pass undefined in React's onClick handler?

I just tried and everything still works, but I can't find any line about that in docs.

Example:

function MonthBar(props) {
  /* is it okay when props.onClick === undefined ? */
  return <span onClick={props.onClick}>{props.monthName}</span>;
}

MonthBar.propType = {
  onClick:  React.PropTypes.func, // optional                   
  monthName: React.PropTypes.string.isRequired
};

Upvotes: 7

Views: 2879

Answers (2)

Chris
Chris

Reputation: 17535

It's perfectly valid to pass in undefined as the onClick handler. They already have to handle that case implicitly since it's an optional parameter.

Upvotes: 8

Md.Estiak Ahmmed
Md.Estiak Ahmmed

Reputation: 1593

passing undefined can be handled by checking it on your onClick,

function MonthBar(props) {
/* is it okay when props.onClick === undefined ? */
  return (
   <span onClick={props.onClick !== undefined? props.onClick : ''}>
    {props.monthName}
   </span>);
}

MonthBar.propType = {
  onClick:  React.PropTypes.func, // optional                   
  monthName: React.PropTypes.string.isRequired
}; 

the concern should be more about you want to pass the undefined to the onClick or not

Upvotes: 0

Related Questions