Key React Native Components
- View: This is a container that supports layout with flexbox, style, and touch handling.
- Text: Used to display text on the screen.
- TextInput: This component is essential for collecting user input, such as in forms.
- Button: Used to trigger actions, like submitting a form or navigating to another screen.
Example of a simple React Native component:
import React from 'react';
import { View, Text, TextInput, Button } from 'react-native';
const MyComponent = () => {
return (
<View>
<Text>Hello, React Native!</Text>
<TextInput
placeholder="Enter your name"
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
/>
<Button title="Submit" onPress={() => alert('Button pressed')} />
</View>
);
};
export default MyComponent;
Explanation: This simple component shows a greeting message, a text input field where the user can type their name, and a button that displays an alert when pressed.
Introducing Yup & Formik
Yup is a JavaScript schema builder for value parsing & validation. It allows you to define a schema for your form data, specifying rules like required fields, min/max values, string formats & more. Yup schemas are very readable & expressive.
Formik is a small library that helps you deal with forms in React. It manages form state, validation, & submission. Formik works well with Yup for validation.
To use Yup & Formik in your React Native project, first install them via npm:
npm install formik yup
Now you can import them in your form component file:
import { Formik } from 'formik';
import * as Yup from 'yup';
With Yup & Formik in place, you're ready to start building a form with validation. Formik will handle the form state & submission, while Yup will define the validation rules.
How to Add Validation to a Form
To add validation to a form with Formik & Yup:
1. Define your form's initial values
2. Create a validation schema with Yup
3. Render the form with Formik
4. Display error messages
For example:
// Initial form values
const initialValues = {
email: '',
password: '',
};
// Validation schema
const validationSchema = Yup.object().shape({
email: Yup.string().email('Invalid email').required('Required'),
password: Yup.string().min(6, 'Too short').required('Required'),
});
function LoginForm() {
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={values => console.log(values)}
>
{({ handleChange, handleBlur, handleSubmit, values, errors, touched }) => (
<View>
<TextInput
onChangeText={handleChange('email')}
onBlur={handleBlur('email')}
value={values.email}
/>
{touched.email && errors.email &&
<Text>{errors.email}</Text>
}
<TextInput
onChangeText={handleChange('password')}
onBlur={handleBlur('password')}
value={values.password}
secureTextEntry
/>
{touched.password && errors.password &&
<Text>{errors.password}</Text>
}
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
);
}
In this example:
- We define the form's initialValues
- Create a validationSchema with Yup rules
- Render the form using Formik's component & props
- Display error messages when fields are touched & have errors
Formik provides props like handleChange, handleBlur, values, errors & touched to manage the form state & validation.
With this basic setup, the form will display errors if the user enters an invalid email address or password less than 6 characters. You can customize the validation rules & error messages as needed.
React Native State
State in React Native refers to the data that controls the behavior of a component. When the state of a component changes, React Native automatically re-renders the component to reflect the updated data. State is commonly used to manage dynamic data such as user inputs, form values, or UI changes.
Managing State in React Native:
React provides a useState hook (for functional components) and this.setState() (for class components) to manage state.
Example of using useState for form validation in React Native:
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
const FormValidation = () => {
const [name, setName] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const handleSubmit = () => {
if (!name) {
setErrorMessage('Name cannot be empty');
} else {
setErrorMessage('');
alert('Form Submitted');
}
};
return (
<View>
<TextInput
placeholder="Enter your name"
value={name}
onChangeText={(text) => setName(text)}
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
/>
{errorMessage ? <Text style={{ color: 'red' }}>{errorMessage}</Text> : null}
<Button title="Submit" onPress={handleSubmit} />
</View>
);
};
export default FormValidation;
Explanation:
- useState: We define two state variables: name to hold the input value and errorMessage to hold the validation error message.
- Form Validation: When the user presses the "Submit" button, the handleSubmit function checks if the name is empty. If it is, an error message is displayed; otherwise, the form is submitted.
Expo CLI
Expo is a toolchain built around React Native that simplifies the development process. It provides a set of libraries and services that make it easy to build, test, and deploy React Native applications. One of the key advantages of using Expo is that it eliminates the need for setting up a complex development environment, which can be challenging for beginners.
How to Set Up Expo CLI:
1.Install Node.js: Make sure you have Node.js installed on your computer. You can download it from here.
2.Install Expo CLI: Run the following command to install Expo CLI globally:
npm install -g expo-cli
3.Create a New Project: To start a new React Native project, run:
expo init my-new-project
Select a template (e.g., "blank") and follow the prompts.
4.Run the Project: To run the project on your emulator or physical device, navigate to your project directory and run:
expo start
Expo provides a QR code in the terminal that you can scan with the Expo Go app (available on both Android and iOS). This allows you to see your app running in real-time without needing to configure a full React Native environment.
Example of Validating a Form Using React Native and Expo
Now, let’s combine React Native and Expo to create a form that validates user input.
Step-by-Step Example:
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
const App = () => {
const [email, setEmail] = useState('');
const [emailError, setEmailError] = useState('');
const validateEmail = (email) => {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
};
const handleSubmit = () => {
if (!email) {
setEmailError('Email is required');
} else if (!validateEmail(email)) {
setEmailError('Please enter a valid email');
} else {
setEmailError('');
alert('Form Submitted Successfully');
}
};
return (
<View>
<TextInput
placeholder="Enter your email"
value={email}
onChangeText={(text) => setEmail(text)}
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
/>
{emailError ? <Text style={{ color: 'red' }}>{emailError}</Text> : null}
<Button title="Submit" onPress={handleSubmit} />
</View>
);
};
export default App;
Explanation:
- Email Validation: This example checks if the email input is valid using a regular expression. If the email is invalid, it shows an error message.
- Expo Integration: Since we used Expo to create and run this project, we can quickly test it on a physical device by scanning the QR code.
Frequently Asked Questions
What is React Native used for?
React Native is a framework that allows developers to build mobile applications for Android and iOS using JavaScript and React.
How do you handle state in React Native?
State in React Native is managed using the useState hook in functional components or this.setState() in class components. It helps manage dynamic data such as user inputs and form values.
What is Expo CLI and why should I use it?
Expo CLI is a tool that simplifies the development and deployment of React Native applications. It eliminates the need to set up a native development environment, making it ideal for beginners.
Conclusion
In this article, we discussed React Native, focusing on form validation, state management, and how to use Expo CLI for building and running mobile applications. By now, you should have a solid understanding of how to create a basic form with validation and handle user input efficiently in React Native. We also discussed Expo CLI, a powerful tool for simplifying the development process.
You can also check out our other blogs on Code360.