Component in react not rendered when .map () function

I am researching react and shorthand for web application development (using egghead.io courses from Dan and Joe) and there is something that I can't get to work even after watching the courses several times

I am basically trying to render an array of items using the .map () function and nothing gets rendered, I loop through the array right after to check if re-rendering starts with the correct state. Here is the code in question:

{TaskManagerStore.getState().tasks.map(task =>
    <Task key={task.id} task={task} />
)}
{TaskManagerStore.getState().tasks.map( task =>
    console.log(task)
)}

<AddTaskButton onClick={() => (
    TaskManagerStore.dispatch({
        type: 'ADD_TASK',
        title: 'Test task',
        content: 'Hey there!',
        id: testID++
    })
)}/>

      

The console log prints all the elements in the array (first nothing, then 0, then [0, 1], etc.), but the component is not displayed. I have placed the console log inside the component render method and it is never called

How can console.log work in .map () but not render the component?

EDIT: Full TaskManager component: https://gist.github.com/Kylar13/6e9b58852f22b64fe5281ed905bf2bc4

EDIT 2: task component:

const Task = ({ task }) => {

    return (
        <div className="Task">
            <h3 className="Task-title">{task.title}</h3>
            <p className="Task-content">{task.content}</p>
            <div className="Task-editButton">Edit<i className="fa fa-pencil" aria-hidden="true"/></div>
        </div>
    )
};

      

+3


source to share


3 answers


Maybe you just need to call Task as a function, for example:



const Task = ({ task }) => {

    return (
        <div key={task.id} className="Task">
            <h3 className="Task-title">{task.title}</h3>
            <p className="Task-content">{task.content}</p>
            <div className="Task-editButton">Edit<i className="fa fa-pencil" aria-hidden="true"/></div>
        </div>
    )
};

{TaskManagerStore.getState().tasks.map(task => Task({ task })}

      

0


source


In the Task component, you pass two props, a key and a task. I solved the problem by adding an extra tooltip that links directly to the state tree, like this ...

const tasks = TaskManagerStore.getState().tasks

{tasks.map(task =>
    <Task 
      key={task.id} 
      task={task} 
      tasks={tasks}/>
)}

      



This is certainly not an elegant solution, but for some reason I cannot get the components generated by the .map () function to re-render without accessing the state directly. If anyone knows why I would love to hear this!

0


source


The map function requires a return for rendering. I think this should do the job.

{TaskManagerStore.getState().tasks.map(task =>
    return <Task key={task.id} task={task} />
)}

      

0


source







All Articles