I'm a React/ES6 beginner and I'm using this code I found to handle a checkbox inside a custom component being clicked (the custom component includes a material-ui CheckBox, hence the "checked" value). I'm planning on adding more fields to the custom component, such as a textbox that corresponds to the checkbox where the user can add more information about the box they checked.
Anyway, I'm a bit confused about what's going on in that first line. I was hoping one of you senior level devs could break it down for me so i can understand what's happening here.
Two things to note:
checked is false by default but console logs as true (is it being toggled true somehow?)
const onMediaDeliverableChange = index => ({ target: {checked} }) => {
console.log('>> [form.js] (onMediaDeliverablesChange) index = ',index);
console.log('>> [form.js] (onMediaDeliverablesChange) target = ',checked); }
Here's an example of code that I took this from, that is working.
const onCheckBoxChange = index => ({ target: { checked } }) => {
const newValues = [...values];
const value = values[index];
newValues[index] = { ...value, checked };
console.log('>> [form.js] (onCheckBoxChange) value = ',value, index);
console.log('>> [form.js] (onCheckBoxChange) newValues[index] = ',newValues[index]);
props.setDesignOrDigital(newValues);
};
The following:
const onCheckBoxChange = index => ({ target: { checked } }) => {
// stuff
};
could also be written as:
const onCheckBoxChange = index => (event) => {
const checked = event.target.checked;
// stuff
};
{ target: { checked } }
is an example of using object destructuring on a function argument. In this case, the argument would be an event.
The first part:
index => another-function
is, as svey mentioned in the comments, an example of a curried function. I assume onCheckBoxChange was used in a loop where the index of the checkbox being rendered was passed in which then returns a function that is an event handler for the change event. The index
is then used to get/set the checked state for the respective checkboxes.