physicsboy
physicsboy

Reputation: 6348

Can't display what is held in State property, but can display what I add to it - ReactJS

Please find my code at this link

I am writing a simple todo list (basically crud) on my own after watching a tutorial, so that I can get to grips with React properly.

After playing around with the code, I eventually had it where the pre-populated list of tasks were being displayed - but I could not add anything to the list.

Now however, I can add things to the list (which is good) - but I can't seem to display the pre-populated items within the list (which is bad).

I feel that my main culprit is the following, but I'm not sure what is going on:

ListBody

displayTasks() {
    return this.props.tasks.map((task, index) =>
      <ListItem key={index} {...task} />
    );
  }

  listTasks() {
    console.log(this.props.tasks);
  }

  render() {
    return(
      <div>
        <button onClick={this.listTasks.bind(this)}>list</button>
        {this.displayTasks()}

      </div>
    )
  }

ListItem

render() {
    return (
      <div>
        {this.props.task}
      </div>
    )
  }

Update

After some further investigation - I was creating an edit/delete button for each entry - To which I found that the 3 pre-populated tasks in my list actually displayed the buttons, but not the text of the task itself...

enter image description here

Upvotes: 0

Views: 55

Answers (3)

xjmdoo
xjmdoo

Reputation: 1736

I could make your example code work with a few modifications:

//list-item.js
class ListItem extends React.Component {

  render() {
    return (
      <div>
        {this.props.task.name}
      </div>
    )
  }
}

//list-body.js
class ListBody extends React.Component {

  displayTasks() {
    return this.props.tasks.map((task, index) =>
      <ListItem key={index} task={task} />
    );
  }

//app.js
createTask(task) {
    console.log('Creating task...');
    console.log(task);

    this.setState((prevState) => {
      prevState.tasks.push({ name: task, isComplete: false });
      return {
        tasks: prevState.tasks
      }
    })

    this.printTasks();

}

Here is the working demo: link

Upvotes: 0

MukulSharma
MukulSharma

Reputation: 221

var that = this 

 <ListItem key={index}  onClick={that.listTasks.bind(task)  />

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67336

You are spreading all the task properties onto ListItem when it looks like you want to just set a task prop. Try this instead:

<ListItem key={index} task={task} />

Upvotes: 1

Related Questions