3

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;
3
  • what's the output you are expecting vs what you are getting. Commented Nov 19, 2022 at 12:44
  • I expect an array of inputs, but I am getting value for the last inputs. Commented Nov 19, 2022 at 23:36
  • @LavkushTari was my answer useful or do you still need help? Commented Nov 22, 2022 at 16:12

1 Answer 1

1

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"
   }
}

Edit restless-cookies-qdgohq

Sign up to request clarification or add additional context in comments.

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.