I tried to find the meaning of “key” property in Meteor, but it’s really hard.
So I try to set up this question for everybody. In 2: Collections | Meteor React Tutorial it sets up a property “key” for a field:
It is really uncovered, what and where is going to use this property. Later on, I see _id field going automatically to functions at 4: Update and Remove | Meteor React Tutorial:
const toggleChecked = ({ _id, isChecked }) – is somehow accepting an _id as first input, but I see nowhere anybody sending it.
const deleteTask = ({ _id }) – this is also getting _id property somehow.
Can someone remove this magic by explaining, where these _id fields come from and what is the meaning of “key” property and where one can find it in manual - google search gives results quite far away when I look for “meteor key property”.
@tambetvali The key property you are referring to is a required attribute to be passed when working with lists on React, it’s not from Meteor. You can read more here: ReactJS | Keys - GeeksforGeeks.
For your other question, you need to understand how the props goes through the component layers.
const deleteTask = ({ _id }) => TasksCollection.remove(_id);
export const App = () => {
..
<ul>
{ tasks.map(task => <Task
key={ task._id }
task={ task }
onCheckboxClick={toggleChecked}
onDeleteClick={deleteTask}
/>) }
</ul>
..
}
The deleteTask
expects to receive an object with the _id
property, which is using the destructuring assignment (Destructuring assignment - JavaScript | MDN). Then we pass this function to the <Task/>
component, with the onDeleteClick
prop (https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function). Then on the Task
component itself, we call this function when the button is clicked:
import React from 'react';
export const Task = ({ task, onCheckboxClick, onDeleteClick }) => {
return (
..
<span>{task.text}</span>
<button onClick={ () => onDeleteClick(task) }>×</button>
..
Is the onDeleteClick(task) passing all the arguments to deleteTask, so I’m then calling deleteTask(task) from there indirectly?
@matheusccastro I mean, I don’t see a direct place, where deleteTask gets input. Only onDeleteClick gets input. Is this input from onDeleteClick sent directly further to the next function in a row? If I assign another variable to onDeleteClick, would I get a different result (I’m going to test this, when I’m near that computer). Is onDeleteClick={deleteTask} taking arguments from onDeleteClick and providing them directly to deleteTask?
Actually the onDeleteClick
function is the deleteTask
function. So when you call (task => onDeleteClick(task))
you are actually calling task => deleteTask(task)
. So yeah, if you change the function you pass to the onDeleteClick
it will change the results too.
@matheusccastro Thanks, now I can understand.