Skip to content

Instantly share code, notes, and snippets.

@sadam1807
Last active February 28, 2023 10:12
Show Gist options
  • Save sadam1807/80f435423730adc7d1fd9b04489374a1 to your computer and use it in GitHub Desktop.
Save sadam1807/80f435423730adc7d1fd9b04489374a1 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react'
import './styles.css'
const App = () => {
const [formValues, setFormValues] = useState([{ name: "", email : ""}])
let handleChange = (i, e) => {
let newFormValues = [...formValues];
newFormValues[i][e.target.name] = e.target.value;
setFormValues(newFormValues);
}
let addFormFields = () => {
setFormValues([...formValues, { name: "", email: "" }])
}
let removeFormFields = (i) => {
let newFormValues = [...formValues];
newFormValues.splice(i, 1);
setFormValues(newFormValues)
}
let handleSubmit = (event) => {
event.preventDefault();
alert(JSON.stringify(formValues));
}
return (
<form onSubmit={handleSubmit}>
{formValues.map((element, index) => (
<div className="form-inline" key={index}>
<label>Name</label>
<input type="text" name="name" value={element.name || ""} onChange={e => handleChange(index, e)} />
<label>Email</label>
<input type="text" name="email" value={element.email || ""} onChange={e => handleChange(index, e)} />
{
index ?
<button type="button" className="button remove" onClick={() => removeFormFields(index)}>Remove</button>
: null
}
</div>
))}
<div className="button-section">
<button className="button add" type="button" onClick={() => addFormFields()}>Add</button>
<button className="button submit" type="submit">Submit</button>
</div>
</form>
)
}
export default App
@Samuel-kedir
Copy link

You 100% solved the problem I was facing.

@tarunverma3116
Copy link

You 100% solved the problem I was facing.

@BG-Allen-Fang
Copy link

thanks you helped me a lot

@CaprettaD
Copy link

Tnks mate. You teach me.

@StoneAge-Inverter-X
Copy link

thanks a lot dude. you are ......can't express enough

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment