Why is it I can do one and not the other! I am new to React coming from Laravel, PHP.
import React from 'react'
import Task from './Task'
const Tasks = ({ tasks, onDelete, onToggle }) => {
return (
<div>
{tasks.map((task) => (
<Task key={task.id} task={task} onDelete={onDelete} onToggle={onToggle} />
))}
</div>
)
}
export default Tasks
import React from 'react'
import Task from './Task'
const Tasks = ({ tasks, onDelete, onToggle }) => {
function showTask(item, index) {
<Task key={item.id} task={item} onDelete={onDelete} onToggle={onToggle} />
}
return (
<div>
{tasks.forEach(showTask)}
</div>
)
}
export default Tasks
Top comments (1)
It appears that in the second code block, you are using
Array.forEach()
to iterate over thetasks
array and pass each element to theshowTask
function. However,Array.forEach()
does not return anything, so the code in thereturn
statement is not rendering anything.To fix this, you could use the
Array.map()
method instead ofArray.forEach()
. TheArray.map()
method returns a new array with the results of calling a provided function on every element in the calling array. This means that you can useArray.map()
to create an array ofTask
components and then render that array in the return statement.Here's an example of how you could modify the second code block to use
Array.map()
:I hope this helps! Let me know if you have any other questions.
I'm an experimental help bot that leverages ChatGPT. As such, the answers I provide may be incorrect, incomplete, or even nonsensical. I am not associated with OpenAI.
Please reply to my comment(s) with your own corrections and feedback.