If you're just getting started with building full-stack web apps using Flask (Python) for your backend and React for your frontend, you might be wondering how to handle forms smoothly. Don't worry, that’s where Formik comes in.
What is Formik?
It's a very useful library for managing forms in React.
What We’re Building...
A basic registration form where a user enters their email and password.
The form will:
- Validate input using Formik and Yup
- Send the data to a Flask backend using fetch( ).
- Handle the response from Flask and show a success or error message.
Step 1:
Flask Backend Setup
Here’s a simple Flask backend that accepts form data from the frontend.
# app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Allows requests from your React app (very important!)
@app.route('/api/register', methods=['POST'])
def register():
data = request.get_json()
# Simple validation
if not data.get('email') or not data.get('password'):
return jsonify({'error': 'Email and password are required.'}), 400
# In a real app, you'd save the data to a database here
print("Received data:", data)
return jsonify({'message': 'Registration successful!'}), 200
if __name__ == '__main__':
app.run(debug=True)
Run this with:
python app.py
Step 2:
React Frontend with Formik (Using fetch)
Now we will build the form in React using Formik for dynamically rendering inputs, and Yup for validation schema.
First, install the necessary libraries in your project:
#in your React frontend
npm install formik yup
#in your Flask backend
pip install Flask flask-cors
Then, create the form:
// RegisterForm.jsx
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const RegisterForm = () => {
const initialValues = {
email: '',
password: ''
};
const validationSchema = Yup.object({
email: Yup.string().email('Invalid email format').required('Required'),
password: Yup.string().min(6, 'Password must be at least 6 characters').required('Required')
});
const handleSubmit = async (values, { setSubmitting, resetForm }) => {
try {
const response = await fetch('http://localhost:5000/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
});
const data = await response.json();
if (!response.ok) {
alert(`Error: ${data.error}`);
} else {
alert(data.message);
resetForm();
}
} catch (error) {
alert('Something went wrong. Please try again.');
} finally {
setSubmitting(false);
}
};
return (
Register
Email:
Password:
Submit
);
};
export default RegisterForm;
What’s Happening Here:
- Formik manages the form’s state and handles submission for you.
- Yup checks that the email is valid and the password isn’t too short.
- We use fetch() to send the form data as JSON to our Flask server.
- Flask checks the data and sends back a JSON response.
If everything goes well, we show a success message . If not, we show an error.
Core Takeaways:
Formik makes working with forms in React much easier, and it works really well with a Flask backend. With just a few lines of code (or 100 lines, depending on the form you're trying to build...), you can build a working form that validates user input and connects to your backend.
Sources:
Formik Docs