I'am working on a react native project and I'am trying to register a form with radio buttons with react-hook-form library. But the defaultValues object of useForm() don't take into account the state update of radio value however I console.log the state and the update works Here the full code:
import React, { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Radio } from "native-base";
const myForm = () => {
//Create an array of all items
const itemsTab = [
{
label: "item 1",
value: "1",
},
{
label: "item 2",
value: "2",
},
{
label: "item 3",
value: "3",
},
];
const [itemChecked, setItemChecked] = useState("");
const { handleSubmit, control, reset } = useForm({
defaultValues: { itemValue: itemChecked },
});
const submitForm = values => {
console.log(values);
};
console.log(`ok: ${itemChecked}`);
return (
<View>
{/* title */}
<Text>list of items</Text>
{/* radio buttons */}
{itemsTab.map((item, index) => {
const { label } = item;
return (
<View key={index}>
<TouchableOpacity onPress={() => setItemChecked(value)}>
<View style={styles.radioBox}>
<Controller
name="itemValue"
control={control}
as={
<Radio
// name="itemValue"
selected={itemChecked === item.value}
color="rgba(0,0,0,.5)"
selectedColor=red
/>
}
/>
<Text>{label}</Text>
</View>
</TouchableOpacity>
{/* submit button */}
<TouchableOpacity
onPress={handleSubmit(submitForm)}
>
<Text>
submit
</Text>
</TouchableOpacity>
</View>
);
})}
</View>
);
};