Anas
Anas

Reputation: 61

How to concatenate new form item into existing state array

This is my react code and I want to concatenate my new form input to existing state array on button click I tried to concatenate state array with different methods but it isn't working, can anyone help me in this regard:

import { useState } from 'react';
import './App.css';

let App = ()=>{

const [initial, addInitial] = useState('');
const [val, addVal] = useState(["Banana"]);

  let changeHandler = (e)=>{
    addInitial(e.target.value)
  }

  let addItem =()=>{

      let newItem = initial;
        
  }

    return(
    <div id="parent">
        <div id="container">
            <h1>To-Do List</h1>

          <div id="sub1">
            <input type="text" value={initial} onChange ={changeHandler} placeholder='Add a item' autoFocus/>
            <button id="add" onClick = {addItem}>+</button>
          </div>
          
            
          <div id="sub2">
            
            {
              val.map((name, index)=>{
                return(
                  <div id="cross" key={index}> 
                    <button id="remove">&#10060;</button>
                    {name}
                  </div>
                )})
            }

          </div>
        </div>
    </div>
    )
}

export default App;

Upvotes: 0

Views: 28

Answers (1)

Pratik Wadekar
Pratik Wadekar

Reputation: 1274

In your addItem() method use this

let addItem = () => {
  addVal(prevValues => [...prevValues, initial]);
};

Upvotes: 1

Related Questions