1

Simply, I am trying to take the user's input and push them into an array. The script itself starts with clicking a button, typing a text input, and clicking to repeat the process. How would I be able to get each input from the user? Would it be possible while keeping my Array.from(Array...) or do I try something else.

import React, {useState} from 'react';
import '../Mentor/PageLayout.css'

var mainArray = ["one", "two"];

function MentorQuiz() {
    const [counter, setCounter] = useState(0);

    const [InputDATA, setInputData] = useState("");

    const handleString = (text) => {
      let InputDATA = text;
      setInputData(InputDATA);
      mainArray.push(InputDATA.toString());
      console.log(mainArray);
    }
  
    const handleClick = () => {
      setCounter(counter + 1);
      console.log(counter);
    };

    return (
      <div className="App">
        <button onClick={() => {
          handleString("Hi");
          handleClick();
        }}> Hello</button>
  
        {Array.from(Array(counter)).map((c, index) => {
          return <input key={c} type="text"></input>;
         
        })}


      </div>
    );
}

export default MentorQuiz;
// I have tested with the OnClick fucntion in my return with handleString("Hi") and I get a //console.log of "Hi". But how do I try with my array?

1 Answers1

1

I think you can do like this:

<input onChange={(e) => setInputData(e.target.value)} />
<button onClick={addUserName}>User Info Entry</button>

For addUserName method:

const addUserName = () => {
   if(inputDATA !== ""){
    mainArray.push(inputDATA);
    // or using spread operator
    // mainArray = [...mainArray, inputDATA];
    setInputData("")
    return;
   }
   alert("Empty Field")
  }
Sujit Libi
  • 386
  • 1
  • 4
  • 16