I want to make a form in react native using Form Hooks. It doesn't work for me.
I have installed hook form with this command:
npm install react-hook-form
And here is my code:
import React from "react";
import { useForm } from "react-hook-form";
const InscriptionScreen = () => {
return (
<form>
<input type="text" placeholder="Email" name="email"/>
<input type="password" placeholder="Password" name="password"/>
<input type="submit"/>
</form>
);
};
export default InscriptionScreen
I get this error:
View config not found for name input. Make sure to start component names with a capital letter.
Do I need to do more configurations or is there a missing keyword in my code?
You use HTML elements in React-Native
, you should use the React-Native
elements and also use useForm
, like below:
import React, { useEffect, useCallback } from 'react';
import { View, TextInput, Button } from 'react-native';
import { useForm } from 'react-hook-form';
const InscriptionScreen = () => {
const { register, handleSubmit, setValue } = useForm();
const onSubmit = useCallback(formData => {
console.log(formData);
}, []);
const onChangeField = useCallback(
name => text => {
setValue(name, text);
},
[]
);
useEffect(() => {
register('email');
register('password');
}, [register]);
return (
<View>
<TextInput
autoCompleteType="email"
keyboardType="email-address"
textContentType="emailAddress"
placeholder="Email"
onChangeText={onChangeField('email')}
/>
<TextInput
secureTextEntry
autoCompleteType="password"
placeholder="Password"
onChangeText={onChangeField('password')}
/>
<Button title="Submit" onPress={handleSubmit(onSubmit)} />
</View>
);
};
export default InscriptionScreen;
Take a look at the documentation, you have an example for react-native form ( https://react-hook-form.com/get-started#ReactNative ):
import React from "react";
import { Text, View, TextInput, Button, Alert } from "react-native";
import { useForm, Controller } from "react-hook-form";
export default function App() {
const { control, handleSubmit, errors } = useForm();
const onSubmit = data => Alert.alert(
"Form Data",
JSON.stringify(data),
);
return (
<View>
<Text>First name</Text>
<Controller
as={TextInput}
control={control}
name="firstName"
onChange={args => args[0].nativeEvent.text}
rules={{ required: true }}
defaultValue=""
/>
{errors.firstName && <Text>This is required.</Text>}
<Text>Last name</Text>
<Controller
as={TextInput}
control={control}
name="lastName"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
/>
<Button title="Submit" onPress={handleSubmit(onSubmit)} />
</View>
);
}
In React Native, you don't have the same primitive as HTML (div, form, ...). So you need to use other method such as the Controller
component from react-hook-form
.
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.