Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
};
like image 769
Alex Povar Avatar asked Aug 28 '16 17:08

Alex Povar


People also ask

Which value should you pass to event listener props like onClick?

Pass a Button's Value as a Parameter Through the onClick Event Handler. You might want to pass in the value or name of the button or input element through the event handler.

How do I beat onClick as a prop?

To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .

How do you get onClick value in react?

We set the onClick prop on the button element. Every time the button is clicked, the handleClick function is invoked. To get the value of the input field on button click, we simply access the message state variable in our handleClick function.

Can we use onClick on a component?

The simple App component above has one function called sayHello(), and a single button. The button inside the React component has an onClick event handler attached to it, pointing to our sayHello() function. Doing so will trigger the function every time you click the button.


1 Answers

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.

like image 59
Chris Avatar answered Oct 17 '22 19:10

Chris