Currently learning React, and I am confused as to why this acts the way it does. My App.JS:
import logo from './logo.svg';
import './App.css';
import Header from './components/Header'
import Tasks from './components/Tasks'
import {useState} from 'react'
function App() {
let name = "Max";
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Doctors Appointment',
day: "Feb 5th at 2:30 pm",
reminder: true,
},
{
id: 2,
text: "Meeting at School",
day: "Feb 6th at 1:30pm",
reminder: true,
},
{
id: 3,
text: "Food Shopping",
day: "Feb 5th at 2:30pm",
reminder: false,
},
])
const deleteTask = (id) => {
alert("deleted " id);
}
return (
<div className="container">
<Header />
<Tasks tasks={tasks} onDelete = {deleteTask} />
</div>
);
}
export default App;
Tasks.JS basically just displays Task.js as h3s Task.js:
import {FaTimes} from 'react-icons/fa'
const Task = ({ task, onDelete }) => {
return (
<div className = "task">
<h3>{task.text} <FaTimes style = {{color:'red', cursor:"pointer"}} onClick = {() => onDelete(task.id)}/></h3>
<p>{task.day}</p>
</div>
)
}
export default Task
So I saw the arrow function for onClick = () => onDelete(task.id) and wondered why I couldn't just do onClick = onDelete(task.id) So I tried that and got some unexpected behavior. Basically, upon the page creation i got the alert that each item had been deleted thrice, and then afterwards nothing happened when I clicked it.
Why does this happen? Like how do I explain this behavior? Why is this arrow function needed?
CodePudding user response:
If you just use onClick = onDelete(task.id) it will call onDelete on every render of that component. You're passing the return from that function to onClick. By using the arrow function, you're passing the function itself, so that when a user clicks on your h3, it will then and only then call that function.
Note - not a great idea to put onClicks on elements like h3s for accessibility reasons.
