I am working in react-native and used 'react-hook-forms' for dynamic form creation, but it's returning empty data object, but it should return values typed in input fields. onSubmit function gives an empty values. Please check my below code. please help me...
//InputBox.js. this my dynamic element where I want access its values in AddDirectries.js
import { useForm, Controller } from 'react-hook-form'
const InputBox = ({ fields, fieldName }) => {
let { control } = useForm();
return (
<>
{ fields.field_unit == null ? <Text style={styles.formsTitle}>{fieldName}</Text> :
<Text style={styles.formsTitle}> {fieldName + "(" + fields.field_unit + ")"}</Text>
}
{[...Array(fields.field_count)].map((item, index) => {
return (
<Controller
control={control}
name={'j' + index}
defaultValue=""
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
onChangeText={value => onChange(value)}
value={value}
></TextInput>
)}
/>
)
})
})
</>)
}
export default InputBox;
//AddDirectries.js here I want access TextInput values.
import { useForm } from 'react-hook-form'
import Element from '../components/Element'
import FormJson from '../../From.json'
export const AddDirectories = (props) => {
let { handleSubmit, control, formState: { errors } } = useForm();
const [elements, setElements] = useState([]);
const [keys, setKeys] = useState([]);
const onSubmit = data => console.log(data);
useEffect(() => {
setKeys(Object.keys(FormJson))
setElements(FormJson)
}, [])
return (
<View style={[styles.mainScreen, { backgroundColor: 'transparent' }]}>
{
keys.map((fieldName, index) => {
return <Element fieldName={fieldName} fields={elements[keys[index]]} key={index}></Element>
})
}
<TouchableOpacity onPress={handleSubmit(onSubmit)} style={[styles1.addButton, { marginBottom: 30 }]}>
<Text>ADD</Text>
</TouchableOpacity>
</View>
)
}
//Element.js
const Element = ({fieldName, fields }) => {
switch (fields.field_type) {
case ("TextField"):
return (<InputLocation fields ={fields} fieldName={fieldName} />)
default: return null;
}
}
export default Element;
I just had the same problem. instead of:
<Controller
control={control}
name={'j' + index}
defaultValue=""
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
onChangeText={value => onChange(value)}
value={value}
></TextInput>
)}
/>
spread field into textinput:
<Controller
control={control}
name={'j' + index}
defaultValue=""
render={({ field }) => (
<TextInput
{...field}
onChangeText={value => field.onChange(value)}
value={field.value}
></TextInput>
)}
/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.