Reputation: 11
I am new to ReactJS and have a question regarding usage of inline arrow functions and unable to understand this even after multiple hours of reading JavaScript ES6 arrow function with ReactJS.
const PersonInputs = ({ idx}) => {
return (
<div key={`name-${idx}`}>
<input type="button" value="Remove Person" onClick={() => removePerson(idx)}/>
</div>
);
};
This is my removePerson function defined in a seperate js file:
const removePerson = (index) => {
let updatedPersons = [...personState];
var temp = updatedPersons[index];
updatedPersons = updatedPersons.filter(person => person.name !== temp.name);
setPersonState(updatedPersons);
};
const blankPerson = { name: '', age: '' };
const [personState, setPersonState] = useState([
{ ...blankPerson },
]);
removePerson function requires index as argument, however when i provide as below i get TypeError: temp is undefined.
const PersonInputs = ({ idx}) => {
return (
<div key={`name-${idx}`}>
<input type="button" value="Remove Person" onClick={(idx) => removePerson(idx)}/>
</div>
);
};
I am not able to understand why onClick={(idx) => removePerson(idx)} this causes error, but works with onClick={(idx) => removePerson(idx)}. Can someone please help me on this. Thanks in advance.
Upvotes: 0
Views: 717
Reputation: 13785
onClick
passes a synthetic event, not the index. Remove idx
as the onClick
param:
const PersonInputs = ({ idx}) => {
return (
<div key={`name-${idx}`}>
<input type="button" value="Remove Person" onClick={() => removePerson(idx)}/>
</div>
);
}
Since your function is getting React's synthetic event vs your index, it's tossing a type error as a result.
Upvotes: 1