Streamlining User Input with Formik and Yup in React Native

Getting Started with Formik and Yup

To follow along, you’ll need a basic understanding of React Native and have it set up on your machine. If you’re new to React Native, refer to the official docs to get started. Once you’re ready, create a new React Native project using the following command:

npx react-native init formikExample

Run the project on your simulator or device to ensure it displays the React Native welcome screen.

Creating Forms with Formik and Yup

In this article, we’ll create three forms: a login form, a sign-up form, and a post blog form. These forms will demonstrate the core features of using Formik and Yup to create forms.

Login Form

Our login form will have two inputs for email and password, along with a login button. We’ll start by importing the Formik library and setting up the inputs.


import { Formik } from 'formik';

const LoginForm = () => {
  return (
     {
        // login logic here
      }}
    >
      {({ handleChange, handleBlur, handleSubmit, values }) => (
        
          
          
          

However, our current implementation allows users to submit the form without entering valid email and password values. To fix this, we’ll create a validation schema using Yup to check if the format of inputs is as expected.


import * as Yup from 'yup';

const loginSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
  password: Yup.string().min(6, 'Too short').required('Required'),
});

We’ll also display custom error messages for each check.


{errors.email}
{errors.password}

Sign-up Form

In our sign-up form, we’ll use Formik’s Field component to automatically hook up inputs to Formik. This simplifies our code and makes it easier to read.


import { Field, Formik } from 'formik';

const SignUpForm = () => {
  return (
     {
        // sign-up logic here
      }}
    >
      {({ handleChange, handleBlur, handleSubmit, values }) => (
        
          
          
          
          
          

To validate our sign-up form, we’ll create a validation schema using Yup.


const signUpSchema = Yup.object().shape({
  fullName: Yup.string()
   .matches(/^[a-zA-Z ]*$/, 'Invalid full name')
   .required('Required'),
  phoneNumber: Yup.string()
   .matches(/^\d{10}$/, 'Invalid phone number')
   .required('Required'),
  password: Yup.string().min(6, 'Too short').required('Required'),
  confirmPassword: Yup.string()
   .oneOf([Yup.ref('password'), null], 'Passwords must match')
   .required('Required'),
});

Post Blog Form

Our post blog form will have three fields for title, content, and photo. We’ll use Formik to manage the form state and Yup to validate the inputs.


import { Formik } from 'formik';
import { launchImageLibrary } from 'eact-native-image-picker';

const PostBlogForm = () => {
  const [photo, setPhoto] = useState(null);

  const handleImageSelect = () => {
    launchImageLibrary({ mediaType: 'photo' }, (response) => {
      setPhoto(response);
    });
  };

  return (
     {
        // post blog logic here
      }}
    >
      {({ handleChange, handleBlur, handleSubmit, values, errors }) => (
        
          
          
          

We’ll also add an image selector using react-native-image-picker and update our validation schema to check for photo objects.


const postSchema = Yup.object().shape({
  title: Yup.string().required('Required'),
  content: Yup.string().required('Required'),
  photo: Yup.object().test('fileSize', 'File size exceeds limit', (value) => {
    return value.size <= 1024 * 1024; // 1MB
  }),
});

The Power of Formik and Yup

Formik and Yup offer an easy, understandable, and extensible solution to handling forms in React and React Native. By leveraging these powerful tools, you can create intuitive and functional forms that improve the user experience of your app.

Get the code on GitHub and start building today!

Leave a Reply