This code snippet showcases my attempt at creating a form with the functionality to generate multiple entries of the same form upon a button click. The ultimate goal is to store the input data in an array of objects, where each object corresponds to one complete form submission.
Parent Component
export interface IExperience {
position: string,
location: string,
startDate: string,
endDate: string,
description: string
}
const Experience = () => {
let [preview,setPreview] = useState(false)
let [data,setData] = useState<IExperience[]>([{position: '', location: '', startDate: '', endDate: '', description: ''}]) // Default state is not undefined
let [button,setButton] = useState('Edit')
return (
<div className={styles.visitorContainer}>
<Nav />
{preview ? <Message setPreview={setPreview} data={data} setData={setData} /> : <Preview setPreview={setPreview} data={data} setData={setData} button={button} setButton={setButton}/>}
<Foot />
</div>
)
}
export default Experience
The preview section can be ignored as it is irrelevant to the issue at hand.
Child Component
import React from 'react'
import { ReactNode, useState } from 'react'
import { IExperience } from '.'
import { Preview } from './preview'
export const Message = ( { setPreview }: any, { data,setData }: any ) => {
let [count,setCount] = useState(0)
let formRows: ReactNode = []
const formHandler = (i:number) => {
console.log(data) //The console log indicates that data is undefined
return formRows = [
(<div key={`innerDiv${i}`}>
<div><h2>Entry {i+1}</h2></div>
<div>
<label>Position</label>
<input type="text" placeholder='Engineer' onChange={(e) => setData({...data,position: e.target.value})} value={data.position} /> //Error occurs here (data is undefined)
</div>
</div>)
]
}
const updateHandler = () => {
setCount(prev => prev+1)
}
return (
<div>
<div>
<div>
</div>
<form onSubmit={(e) => sendData(e)}>
{[...Array(count+1)].map((d,i) => (<div key={`outerDiv${i}`} >{formHandler(i)}</div>))}
<div>
<input type="button" value='+' onClick={() => updateHandler()} />
</div>
</form>
</div>
</div>
)
}
I have been exploring this issue for days without finding a solution online, hence turning to posting my own question. Your insights are greatly appreciated!
I hope the code is clear and concise :)