<div id="root">
</div>
const App = () => {
  const [ contactCount, setContactCount ] = React.useState(0)
  const [ contactInfo, setContactInfo ] = React.useState({})
  
  const getContactInputElements = () => {
    let contactInputElements = []
    for (let i = 0; i <= contactCount; i++) {
      contactInputElements.push(
        <div key={i} id={"contact_" + i}>
          <input 
            className="update_contact_info"
            type="text"
            name="first_name"
            placeholder="First Name"
            onChange={handleInput}
           />
          <input 
            className="update_contact_info"
            type="text"
            name="middle_name"
            placeholder="Middle Name"
            onChange={handleInput}
           />
          <input 
            className="update_contact_info"
            type="text"
            name="last_name"
            placeholder="Last Name"
            onChange={handleInput}
           />
        </div>
      )
  }
  return contactInputElements
}

// Single event handler with switch for different events
const handleInput = (e) => {
  let eventClass = e.target.className
  switch(eventClass) {
    case "add_contact":
      setContactCount(contactCount + 1)
      break
    case "update_contact_info":
      let name = e.target.name
      let id = e.target.parentElement.id
      let value = contactInfo[id] ? 
        { ...contactInfo[id], [name]: e.target.value } :
        { [name]: e.target.value }
      let newContactInfo = { ...contactInfo, [id]: value }
      setContactInfo(newContactInfo)
      break
  }
  
}

const showContactInfo = () => {
  return JSON.stringify(contactInfo, undefined, '    ')
}
  
  return (
    <div>
      {getContactInputElements()}
      <button
        className="add_contact"
        onClick={handleInput}>
        Add a contact
      </button>
      <p>contactInfo:</p>
      <pre>{showContactInfo()}</pre>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"))


View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js