Skip to content

Instantly share code, notes, and snippets.

@web2feel
Last active July 15, 2020 08:35
Show Gist options
  • Select an option

  • Save web2feel/ac6ae7e8fd497a15ef2bd7fb397490cc to your computer and use it in GitHub Desktop.

Select an option

Save web2feel/ac6ae7e8fd497a15ef2bd7fb397490cc to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
function DebAp() {
const [inputList, setInputList] = useState([{ fName: "", ltName: "" , hobbys:[] }]);
const handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = [...inputList];
switch(name) {
case 'fName':
list[index].fName = value;
break;
case 'ltName':
list[index].ltName = value;
break;
case 'hobbys':
list[index].hobbys = value.split(',');
break;
default:
}
setInputList(list);
};
const handleRemoveClick = index => {
const list = [...inputList];
list.splice(index, 1);
setInputList(list);
};
const handleAddClick = () => {
setInputList([...inputList, { fName: "", ltName: "",hobbys:[] }]);
};
console.log(inputList);
return (
<div className="App">
{inputList.map((x, i) => {
return (
<div key={i} className="box">
<input
name="fName"
placeholder="Enter first Name"
value={x.fName}
onChange={e => handleInputChange(e, i)}
/>
<input
className="ml10"
name="ltName"
placeholder="Enter Last Name"
value={x.ltName}
onChange={e => handleInputChange(e, i)}
/>
<textarea
name="hobbys"
value={x.hobbys}
onChange={e => handleInputChange(e, i)}
/>
<div className="btn-box">
{inputList.length !== 1 && <button
className="mr10"
onClick={() => handleRemoveClick(i)}>Remove</button>}
{inputList.length - 1 === i && <button onClick={handleAddClick}>Add</button>}
</div>
</div>
);
})}
<div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
</div>
);
}
export default DebAp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment