Skip to content
Advertisement

how to store value of 2 inputs dynamically generated in state at once

i am using react.i have 2 inputs that by clicking a button dynamically ganerats. this the code:

  useEffect(() => {
        const myFields = fieldsArray.map((field) => {
            return (
                <div key={field} className="col-12 m-auto d-flex">
                    <input id={field} name={`question${field}`} onChange={handleChangeFields} placeholder='سوال' className="form-control col-4 m-2" />
                    <input id={field} name={`answer${field}`} onChange={handleChangeFields} placeholder='جواب' className="form-control col-4 m-2" />
                </div>
            )
        })
        setFields(myFields)
    }, [fieldsArray])

i need to save value of 2 inputs together in an opjects like this :

[{question : '',answer : ''}]

and the new 2 input’s value are going to update the above array like this:

[{question : '',answer : ''}, {question : '',answer : ''}]

i can save each input’s value separately like this :

  const handleChangeFields = (e) => {
        const { name, value } = e.target
        setFieldsValue([...fieldsValue, { [name]: value }])
    }

but i want each 2 input’s value together i need to save each 2 inputs together. how do i do that?

Advertisement

Answer

this problem solved for me :

function App() {
  const [results, setResults] = useState([{ question: "", answer: "" }])

  // handle input change
  const handleInputChange = (e, index) => {
    const { name, value } = e.target
    const list = [...results]
    list[index][name] = value
    setResults(list)
  }

  // handle click event of the Remove button
  const handleRemoveClick = (index) => {
    const list = [...results]
    list.splice(index, 1)
    setResults(list)
  }

  // handle click event of the Add button
  const handleAddClick = () => {
    setResults([...results, { question: "", answer: "" }])
  }

  // handle submit to servers
  const handlesubmit = () => {
    // axios
    console.log(results)
  }

  return (
    <div className="App">
      {results?.map((result, index) => {
        return (
          <div key={index}>
            <input
              name="question"
              value={result.question}
              onChange={(e) => handleInputChange(e, index)}
            />
            <input
              name="answer"
              value={result.answer}
              onChange={(e) => handleInputChange(e, index)}
            />
            {results.length !== 1 && (
              <button onClick={() => handleRemoveClick(index)}>
                Remove
              </button>
            )}
            {results.length - 1 === index && (
              <button onClick={handleAddClick}>add</button>
            )}
          </div>
        )
      })}
      <div style={{ marginTop: 20 }}>{JSON.stringify(results)}</div>
      <button onClick={handlesubmit}>submit</button>
    </div>
  )
}

export default App
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement