Reputation: 457
I am working with a checkbox in react.
I am making my checkbox using dynamic data I am getting from a server and accordingly showing checked and unchecked states on the UI.
For form validation, I am using react-form-hook
and for getting data onSubmit, I am using handleSubmit
from react-form-hook
My only issue is that I am not able to get data as per my requirement.
My data:
let dta = [
{
p_id: 2,
p_name: "isco",
isChecked: true
},
{
p_id: 2,
p_name: "david",
isChecked: false
}
];
My form:
<form onSubmit={handleSubmit(submitForm)}>
{dta.map((li, index) => (
<div key={index}>
<input
type="checkbox"
id={li.component_name}
name={`data.${li.p_name}`}
ref={register}
defaultChecked={li.isChecked}
/>
<label htmlFor={li.p_name}>{li.p_name}</label>
</div>
))}
<button>Submit</button>
</form>
On Submit, I am getting data like this
{"data":[{"isco":false},{"david":true}]}
But how I want it is like below
{
"data": [
{
"p_name": "isco",
"isChecked": true,
"p_id":1
},
{
"p_name": "david",
"isChecked": false,
"p_id":2
}
]
}
Edit
Upvotes: 1
Views: 5817
Reputation: 873
i am change code
export default function App() {
let data = [
{
p_id: 1,
p_name: "isco",
isChecked: true
},
{
p_id: 2,
p_name: "david",
isChecked: false
}
];
const [dataForm, setDataForm] = useState(data);
const changeCheck = (id) => {
console.log(id);
let temp = [...dataForm];
const index = temp.findIndex((x) => x.p_id === id);
if (index === -1) return;
temp[index].isChecked = !temp[index].isChecked;
setDataForm(temp);
};
const handleSubmit = () => {
console.log(`{"data":` + JSON.stringify(dataForm) + `}`);
};
return (
<div className="App">
<form>
{dataForm.map((li, index) => (
<div key={index}>
<input
type="checkbox"
checked={li.isChecked}
onChange={() => {
changeCheck(li.p_id);
}}
/>
<label htmlFor={li.p_name}>{li.p_name}</label>
</div>
))}
<button type="button" onClick={handleSubmit}>
Submit
</button>
</form>
</div>
);
}
Work Demo
Upvotes: 1