0

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;

1 Answer 1

1

In your addItem() method use this

let addItem = () => {
  addVal(prevValues => [...prevValues, initial]);
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much dear could you please brief little how its working?
@Anas Look up the usage of spread operator in js
@Anas setState() function in react gives you a callback which has access to previous State Values that can be used to update your existing state. So in the above I used previous state values spread it across the array and added your new value i.e initial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.