M
M
Michael R.2019-05-31 18:28:37
JavaScript
Michael R., 2019-05-31 18:28:37

How to correctly display information from a React component?

Greetings!
After a couple of days of studying React, I wrote a simple application for adding tasks, and in connection with this, a couple of questions appeared:
1. How to show all tasks at once, and not after adding the next task? I tried to process in the controller and in render, it didn't work...
2. What would you change in the code?
I would appreciate any comments, thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-31
@Mike_Ro

class App extends React.Component {
  state = {
    tasks: [
      {
        id: 1,
        title: 'title',
        description: 'description',
      },
    ],
  }

  createTask = () => {
    this.setState(({ tasks }) => ({
      tasks: [
        ...tasks,
        {
          id: 1 + Math.max(0, ...tasks.map(n => n.id)),
          title: 'title',
          description: 'description',
        },
      ],
    }));
  }

  render() {
    return (
      <div>
        <button onClick={this.createTask}>Добавить задачу</button>
        <ul>
          {this.state.tasks.map(({ id, title, description }) => (
            <li key={id}>id: {id} | {title} | {description}</li>
          ))}
        </ul>
      </div>
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question