1

Code:

export default function App() {
  const [name,setName] = useState("");
  var myArray = [];
  const handleAdd = () => {
    myArray = [...myArray,name]
    setName("")
  }
  return (
    <div className="App">
      <input placeholder="type a name" onChange={(e) => setName(e.target.value)}/>
      <button onClick={handleAdd}>add</button> 
      <button onClick={() => console.log(myArray)}>test</button>
      {myArray.map((n) => {
        return <h2>{n}</h2> 
      })}
    </div>
  );
}

OnClick it isn't adding the name to the array.

4 Answers 4

6

this is how you "push" to an array with useState

const [array, setArray] = useState([])
setArray(previous => [...previuous, newItem])
Sign up to request clarification or add additional context in comments.

Comments

1

You should use a state for your array and set that state to see the changes reflected:

export default function App() {
    const [name, setName] = useState('');
    const [myArray, setMyArray] = useState([]);
    const handleAdd = () => {
        setMyArray([...myArray, name]);
        setName('');
    };
    return (
        <div className="App">
            <input
                placeholder="type a name"
                onChange={(e) => setName(e.target.value)}
            />
            <button onClick={handleAdd}>add</button>
            <button onClick={() => console.log(myArray)}>test</button>
            {myArray.map((n) => {
                return <h2>{n}</h2>;
            })}
        </div>
    );
}

Comments

0

We can also set the state of myArr to be an empty array initially, making it easier to manipulate the subsequent state of that array. The onClick event handler does not fire the handleAdd function, for some reason, it only resets the form and does not provide any state. To submit the form and materialize the state, we can also use the onSubmit event handler instead of onClick. In the same way, we can use the name state as a value/prop for the name input, which will be used by the onChange handler.

import React, { useState } from 'react'

const App = () => {
const [name, setName] = useState('')
const [myArr, setMyArr] = useState([])

const submit = (event) => {
  event.preventDefault()
  setMyArr(myArr.concat(name))
  setName('')
}

//console.log(myArr)
return (
  <div className="App">
    <form onSubmit={submit}>
      <div>
         <label htmlFor="name">Name</label>
         <input
           placeholder="type a name"
           type="text"
           value={name}
           onChange={({ target }) => setName(target.value)}
          />
        </div>
      <div>
        <button type="submit">Add</button>
      </div>
    </form>
    <div>
      {myArr.map((arr, index) => (
        <div key={index}>
          <p>{arr}</p>
        </div>
      ))}
    </div>
   </div>
  )
 }

export default App

I have a proclivity of inserting items on an array using concat.

import React, { useState } from 'react'
// ...
const App = () => {

// ...

const [myArr, setMyArr] = useState([])

// somewhere on your event handler e.g. Submit handler
setMyArr(myArr.concat(name))

// ...

}

Comments

0
import React, { useState } from 'react'

  const Final = () => {
   const [input,setInput]=useState("");
  const[array,setArray]=useState([]);

   const handleClick=(e)=>{
     setArray([...array,input]);
      setInput("");
     }
         const Rushabh=(e)=>{
          if(e.key==='Enter'){
          handleClick();
          }
           }
       return (
         <div>
              <input type="text" id="input" placeholder="Name" value= 
         {input} onChange= 
           {(e)=>setInput(e.target.value)} onKeyDown={Rushabh}/>
          <button type="button" onClick={handleClick}>Button</button>

            <p>{array.map((e,index)=>{
              return (
                  <p key={index}>{e}</p>
              )
            })}</p>
           </div>
          )
          }

          export default Final

Comments

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.