Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to state array in React

I am making a simple to-do list app in React. I have 3 states, inputText (the task the user enters), triggerAnimation(to trigger animations), and tasks (the list of tasks user has entered). However I don't know how to update the tasks state (which is an array) to push the new tasks. Here is the code.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      inputText: '',
      triggerAnimation: '',
      tasks: []
    }
  }

//The function triggered by button which sends the task the user has entered to the tasks array state:

  addItem() {
    document.querySelector("#textfield1").value = ""
    this.setState({ 
      triggerAnimation: 'fadein', tasks: 
      this.state.inputText 
    }) 
  }



  render() {
    //Where User enters task:
    return (
      <div className="App">
        <main>
          <div className="enterTask">
            <input type="text" className="inputclass" id="textfield1" 
              placeholder='Enter a task.' 
              onChange={event => this.setState({ 
                inputText: event.target.value })} 
              onKeyPress={event => {
                if(event.key === 'Enter') {
                  this.addItem();
                }
               }} 
             />
            <br />
            <br />
            <button className="button" 
              onClick={() => this.addItem()} data-
                toggle='fadein' data-target='list'>+
            </button>
         </div>


    <!-- Where tasks will appear: -->

         <div className="log">
           <p className='list'>
             <span class={this.state.triggerAnimation}>  
               {this.state.tasks}
             </span>
           </p>
           <button className="button">-</button>
         </div>
       </main>
     </div>
    )
  }
}  

export default App;
like image 379
Usman Avatar asked Feb 14 '18 20:02

Usman


People also ask

How do you add to an array in state React?

Use the spread syntax to push an element into a state array in React, e.g. setNames(current => [... current, 'Carl']) . The spread syntax (...) will unpack the existing elements of the state array into a new array where we can add other elements.

How do I add a state value in React?

To change a value in the state object, use the this. setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).

How do you update state array in React functional component?

However, with React, we need to use the method returned from useState to update the array. We simply, use the update method (In our example it's setMyArray() ) to update the state with a new array that's created by combining the old array with the new element using JavaScript' Spread operator.


3 Answers

However I don't know how to update the tasks state (which is an array) to push the new tasks.

Probably the cleanest way to "push to an array" in state is to use ES6 array spread. The best practice would also be to use the setState callback syntax to ensure the correct state is committed before you push the new task:

this.setState(prevState => ({
  tasks: [...prevState.tasks, newTask] 
}));
like image 97
Aaron Beall Avatar answered Oct 09 '22 21:10

Aaron Beall


Seems like what you want is this..

addItem() {
document.querySelector("#textfield1").value = ""
this.setState({
            triggerAnimation: 'fadein',
            tasks: this.state.tasks.concat(this.state.inputText)}) 
}
like image 22
Shanon Jackson Avatar answered Oct 09 '22 21:10

Shanon Jackson


You can use .concat method to create copy of your array with new data:

  addTask() {
    this.setState({tasks: this.state.tasks.concat(["new value"])})
  }

You also need to bind this to addTask in your constructor:

this.addTask = this.addTask.bind(this)

See my example:

https://jsfiddle.net/69z2wepo/103069/

Documentation: https://reactjs.org/docs/react-component.html#setstate

like image 3
Alex Fallenstedt Avatar answered Oct 09 '22 21:10

Alex Fallenstedt