Handling Forms in React with Formik, Yup, Chakra UI
What is this blog about?
This blog is about handling forms in react, how to abstract the form functionalities into little pieces and make it, umm lets say modular?
What will we be doing here?
We are gonna look at basic form fields like the input field for Text and Email, Radio button, Drop Down fields
Steps
Step 1 : Project setup
create the basic structure of the react app using vite, select react and js as when prompted
npm create vite@latest
move into the folder you just created and install the dependencies
npm install
npm install formik yup
install chakra ui dependencies and configure your application to be styles with chakra ui
npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion @chakra-ui/icons
now change the code in the main.jsx file so that your application has the styles specified by chakra ui and so as to use the utilities it provides
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import { ChakraProvider } from "@chakra-ui/react";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<ChakraProvider>
<App />
</ChakraProvider>
</React.StrictMode>
);
Step 2 : Creating components
Now lets create a components folder in the src folder of out project and also make sure to create fields folder in the components directory
these just to organize our files better
now the basic idea is that we create bare field components for each of the required field and build an intermediate called 'FormikControl' components which when rendered by passing the appropriate props we want for a specific field
the form fields error handling is taken care by chakra ui and formik combined and the handling of form values is taken care by formik itself
yup is used for schema validation
Later on, I'll be adding some complex fields like array field, and conditional selects to the repo and will be writing a post for those too, perhaps this time in a little detail
You can find the code here in this github repository
Here is the resource i used to learn these, credits to the creator
Subscribe to my newsletter
Read articles from Vishnu Teja directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by