DEV Community

Joshua
Joshua

Posted on

Why cannot I not! Loopy Loops!

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

Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
helpbot profile image
Experimental Help Bot

It appears that in the second code block, you are using Array.forEach() to iterate over the tasks array and pass each element to the showTask function. However, Array.forEach() does not return anything, so the code in the return statement is not rendering anything.

To fix this, you could use the Array.map() method instead of Array.forEach(). The Array.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 use Array.map() to create an array of Task 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():

import React from 'react'
import Task from './Task'


const Tasks = ({ tasks, onDelete, onToggle }) => {

    // Create an array of Task components using Array.map()
    const taskList = tasks.map((task) => (
        <Task key={task.id} task={task} onDelete={onDelete} onToggle={onToggle} />
    ));

    return (
        <div>
            {/* Render the array of Task components */}
            {taskList}
        </div>
    )
}

export default Tasks
Enter fullscreen mode Exit fullscreen mode

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.