O
O
OneLiL2021-07-26 23:30:23
React
OneLiL, 2021-07-26 23:30:23

Map doesn't work when pushing to an array, what to do?

There is a code where, when the button is clicked, the element should be pushed into the array, and React renders it using the map operator, the push passes, but the React does not render the element

class Form extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: ""
        }

      this.handleChange = this.handleChange.bind(this);
      this.addTask = this.addTask.bind(this);
      this.handleEnter = this.handleEnter.bind(this);
    }

    handleEnter(event){
      if (event.key === 'Enter'){
        this.addTask()
      };
    }

    addTask() {
      if (this.state.value !== ""){
        this.props.addTask(this.state.value)
      }
      this.setState({value: ""});
    }

    handleChange(event){
      this.setState({value: event.target.value})
    }

    render() {
        return (
          <div className="search-block">
              <input type="text" id="search-input" className="search-input top-space-md" onKeyPress={this.handleEnter} value={this.state.value} onChange={this.handleChange} placeholder="Write a task"/>
              <button id="search-btn" className="search-btn" aria-label="Создать таску" onClick={this.addTask}>
                  Create
              </button>
          </div>
        )
    }
}

function Main()  {

  let tasks = [];

  function addTask(task){
    tasks.push({
      id: tasks.length !== 0 ? tasks.length : 0,
      name: task,
      done: false
    });
    return tasks;
  }

  return (
      <main id="todo" role="main">
        <div className="main-content top-space-md">
          <div className="search-block">
            <Form addTask={addTask}/>
          </div>
          <div className="todo-items">
            {tasks.map(task => {
             return <Task task={task} key={task.id} title={task.name} done={task.done}/>
            })}
          </div>
        </div>
      </main>
    );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TopsterTX, 2021-07-27
@TopsterTX

Try using concat instead of push
function addTask(task){
tasks.concat({
id: tasks.length !== 0 ? tasks.length : 0,
name: task,
done: false
});
return tasks;
}
They both add elements to the array, but push returns (if I'm not mistaken) the entry it changed, and concat returns the changed array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question