'React Hook Form 7 custom ...register values
I need to modify my Controller Checkbox data onSubmit with custom values.
Currently, I can only submit the checked values of the checkbox:
form: Array(2)
0: 18
1: 17
What I want is to pass also all the form.questionID together with the values of form.content, not just the Checked values. Something like this:
form: Array(26)
'form[0].questionId="19"'
'form[1].questionId="18"'
'form[2].questionId="17"'
'form[3].questionId="16"'
'form[4].questionId="15"'
'form[5].questionId="14"'
'form[6].questionId="7"'
'form[7].questionId="8"'
'form[8].questionId="9"'
'form[9].questionId="10"'
'form[10].questionId="11"'
'form[11].questionId="12"'
'form[12].questionId="13"'
'form[0].content="No"'
'form[1].content="Yes"'
'form[2].content="Yes"'
'form[3].content="No"'
'form[4].content="No"'
'form[5].content="No"'
'form[6].content="No"'
'form[7].content="No"'
'form[8].content="No"'
'form[9].content="No"'
'form[10].content="No"'
'form[11].content="No"'
'form[12].content="No"'
Here's my current code:
{element.map((answer, index) => (
<div key={index}>
<Controller
name="Checkbox"
control={control}
render={({ field }) => (
<Checkbox
onChange={(e) => field.onChange(e.target.checked)}
checked={field.value}
value={answer.id}
id={answer.id.toString()}
name={answer.type}
{...register('form')}
/>
)}
/>
{answer.type}
</div>
))}
And finally here is my onSubmit function
const onSubmit = () => {
const data = {
form: getValues('form'),
}}
I tried this solution tho but nothin change
{element.map((answer, index) => (
<div key={index}>
<Controller
name="Checkbox"
control={control}
render={({ value, field }) => (
<Checkbox
onChange={(e) => {
const valueCopy = [...value]
if (e.target.checked) {
valueCopy.push([
{ questionId: answer.id },
{ content: field.value },
]) // append to array
} else if (!e.target.checked) {
valueCopy.push([
{ questionId: answer.id },
{ content: field.value },
])
}
field.onChange(valueCopy) // update form field with new array
}}
checked={field.value}
value={answer.id}
// id={answer.id.toString()}
name={answer.type}
{...register('healthForm')}
/>
)}
/>
{answer.type}
</div>
))}
Solution 1:[1]
I manage to do this but incomplete, anyone?
{...register(
`form.[${index}].content`,)}
Result:
"form": [
{
"content": "Yes"
},
{
"content": "Yes"
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": false
},
{
"content": "Yes"
},
{
"content": "Yes"
}
]
just neede to add questionId in the ...register but not sure how, i tried everything lol.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | savageDeveloper |
