What is the difference between:
const handleChange = (event) => {
setValue(event.target.value);
};
and
const handleChange = (event, newValue) => {
setValue(newValue);
};
? The first seems to work in some cases, and the second in others.
First of all, I want to tell you that you are just passing a function for events like onChange
or onClick
, right? So, this is simple. We can pass any parameters to a function based on our needs. For those events, we basically use the following syntaxes:
const handleChange = (event) => {
setValue(event.target.value);
};
Here handle change is just a normal function, so it is not required that you only have to pass event
as your parameter. It can be anything that you require to process that function. For the above use case, you needed input value that's why you passed the event object as the first param. But, maybe sometimes you will need extra data to work with that function. For example, you have multiple inputs, like below. You can add such inputs by clicking plus icon. And we might be storing data in an array of objects [{trait_type:'', value:''},{trait_type:'',value:''}]
, each array element represents a pair of those input. It will be efficient to use a change handler that accepts both (event and index) of input as params.
What is the main point is you are just passing functions to those events, and you can pass 0 or more parameters. It is not the rule that you have to pass Event
for all event handlers. Yeah, sometimes you might require an Event
object to stop propagating the event. Hope this explanation will help you. Make changes as you needed and best suited for you. Thank you.