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
};
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With