简体   繁体   中英

How to get inputs data from multiple text box in for loop in React js and pass it to Api

I am trying to build a quiz application where I want to generate no of Question input fields based on admin inputs.

So suppose the admin enters 10 questions for the quiz.

Then I am rendering the form inside for loop for 10 Questions and their answers respectively.

The problem I am facing is I am not able to get all values from input fields.

Below is my demo code:

import { useState } from "react";
const MyComponent = () => {
  const [inputs, setInputs] = useState({});
  const handleChange = (e) =>
    setInputs((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value
    }));

  const finalData = (e) => {
    e.preventDefault();
    console.log("data", inputs);
  };

  function buildRows() {
    const arr = [];
    for (let i = 1; i <= 3; i++) {
      arr.push(
        <div key={i} id={i}>
          <input name="Question" onChange={handleChange} />
          <input name="option1" onChange={handleChange} />
          <input name="option2" onChange={handleChange} />
          <input name="option3" onChange={handleChange} />
          <input name="option4" onChange={handleChange} />
        </div>
      );
    }
    return arr;
  }
  return (
    <>
      {buildRows()}
      <button
        onClick={(e) => finalData(e)}
        variant="contained"
        className="button-left"
        sx={{ marginRight: 3.5 }}
      >
        Submit Quiz Questions
      </button>
    </>
  );
};
export default MyComponent;

You could use the id (or any other unique property, a unique name would probably be preferred) you're giving your div and build your object with that as an array index like so:

const handleChange = (e) => {
  const parent = e.currentTarget.parentNode;
  const id = parent.id;
  setInputs((prevState) => ({
    ...prevState,
    [id]: {
      ...prevState[id],
      [e.target.name]: e.target.value
    }
  }));
};

This produces an object like this:

{
   "1":{
      "Question":"1",
      "option1":"2",
      "option2":"3",
      "option3":"4",
      "option4":"5"
   },
   "2":{
      "Question":"6",
      "option1":"7",
      "option2":"8",
      "option3":"9",
      "option4":"11"
   },
   "3":{
      "Question":"22",
      "option1":"33",
      "option2":"44",
      "option3":"55",
      "option4":"66"
   }
}

编辑 restless-cookies-qdgohq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM