@emacapt/widget-react
v0.0.9
Published
@emacapt/widget-react is a customizable, accessible, and easy-to-use form widget for React applications. It provides a pop-up modal form with various field types, customizable styling, and built-in validation.
Downloads
11
Readme
@emacapt/widget-react
@emacapt/widget-react is a customizable, accessible, and easy-to-use form widget for React applications. It provides a pop-up modal form with various field types, customizable styling, and built-in validation.
Features
- 🎨 Customizable styling
- 📱 Responsive design with mobile-friendly layout
- ♿ Accessibility-ready with proper ARIA attributes
- 🔒 Supports both server-side (Next.js API Routes) and client-side API calls
- 🔢 Various input types: text, email, number, checkbox, select
- ✅ Built-in and custom validation support
- 🌈 Easy theming with primary color selection
Installation
Install the package using npm:
npm install @emacapt/widget-react
Usage
There are two ways to use the EmacaptWidget: with a server-side endpoint (recommended for security) or with direct API calls. You must choose one of these methods. Email field is mandatory and will be automatically added to the form.
Server-Side Usage (Recommended for Security)
Use @emacapt/widget-react with a Next.js API route:
- Create an API route (e.g.,
pages/api/submit-form.ts
):
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (req.method !== "POST") {
return res.status(405).json({ message: "Method Not Allowed" });
}
const formData = req.body;
try {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('X-Project-Api-Key', process.env.API_KEY ?? '');
const response = await fetch('https://api.emacapt.com/clients', {
method: 'POST',
headers,
body: JSON.stringify(formData)
});
if (!response.ok) {
throw new Error("API request failed");
}
const data = await response.json();
return res.status(200).json(data);
} catch (error) {
console.error("Error submitting form:", error);
return res
.status(500)
.json({ error: "An error occurred while submitting the form" });
}
}
- Use the widget in your React component:
import React from "react";
import { EmacaptWidget, createField, validations } from "@emacapt/widget-react";
const MyForm = () => {
const fields = [
// Note: You don't need to include an email field, it's automatically added
createField({
name: "name",
label: "Full Name",
type: "text",
required: true,
}),
createField({
name: "message",
label: "Message",
type: "text",
required: false,
}),
];
const customTextOptions = {
openFormButton: "Contact Us",
submit: "Send Message",
success: "Thank you for your message!",
};
const handleSuccess = (data) => {
console.log("Form submitted successfully:", data);
};
const handleError = (error) => {
console.error("Error submitting form:", error);
};
return (
<div>
<h1>My Contact Form</h1>
<EmacaptWidget
serverEndpoint="/api/submit-form"
fields={fields}
primaryColor="indigo"
textOptions={customTextOptions}
onSuccess={handleSuccess}
onError={handleError}
/>
</div>
);
};
export default MyForm;
Client-Side Usage (Less Secure)
For scenarios where server-side processing is not possible, you can use the widget with direct API calls. However, this method is less secure as it exposes your API key to the client.
import React from "react";
import { EmacaptWidget } from "@emacapt/widget-react";
const MyForm = () => {
// ... rest of the component logic
return (
<EmacaptWidget
apiKey="your-api-key-here"
apiUrl="https://api.emacapt.com/submit-form"
primaryColor="indigo"
textOptions={customTextOptions}
onSuccess={handleSuccess}
onError={handleError}
/>
);
};
export default MyForm;
Configuration Options
Props
You must provide either serverEndpoint
or both apiKey
and apiUrl
:
serverEndpoint
(string, recommended): The endpoint for your server-side API route.apiKey
(string, less secure): Your API key for direct API calls.apiUrl
(string, less secure): The URL to submit the form data to.
Other props:
fields
(Field[]): An array of field configurations. Note: An email field is automatically added and does not need to be included in this array.primaryColor
(string, optional): The primary color theme ('blue', 'indigo', 'green', or 'red'). Default is 'blue' or put your own color value as hex string, e.g "#0066ff".textColor
(string, optional): The color of the text in the form. Default is 'white'.textOptions
(Partial, optional): Customized text for various parts of the widget.onSuccess
(function): Callback function called when form submission is successful.onError
(function): Callback function called when an error occurs during form submission.
Field Configuration
Fields are typically configured using the createField
helper function and preset validations. However, you can also manually create fields and provide custom validation functions if needed.
import { createField, validations } from "@emacapt/widget-react";
const fields = [
// Note: You don't need to include an email field, it's automatically added
createField({
name: "name",
label: "Full Name",
type: "text",
required: true,
}),
createField({
name: "age",
label: "Age",
type: "number",
required: true,
validation: (value: number) => {
return value >= 18 ? null : "You must be 18 or older";
},
}),
createField({
name: "preferences",
label: "Preferences",
type: "select",
options: [
{ value: "option1", label: "Option 1" },
{ value: "option2", label: "Option 2" },
],
required: false,
}),
// ... other fields
];
return (
<EmacaptWidget
apiKey="your-api-key-here"
apiUrl="https://api.emacapt.com/submit-form"
fields={fields} // put fields here
textOptions={customTextOptions}
onSuccess={handleSuccess}
onError={handleError}
/>
);
Submission Data Structure
When the form is submitted, the data will be structured as follows:
{
email: string,
data: {
[fieldName: string]: string | number | boolean
}
}
The email
field is automatically included at the top level, and all other fields are included in the data
object.
Text Customization
Customize the widget's text by passing a textOptions
object:
const customTextOptions = {
openFormButton: "Contact Us",
submit: "Send",
submitting: "Sending...",
success: "Thank you!",
error: "Oops! Something went wrong.",
requiredField: "This field is required",
invalidEmail: "Please enter a valid email",
selectPlaceholder: "Choose an option",
modalTitle: "Get in Touch",
modalSubheading: "We'd love to hear from you!",
closeButtonAriaLabel: "Close form",
};
Styling
The widget uses Tailwind CSS for styling. The necessary styles are included in the package, so you don't need to import any additional CSS files.
Accessibility
@emacapt/widget-react is designed with accessibility in mind, including proper ARIA attributes and keyboard navigation support. However, always test your implementation to ensure it meets your specific accessibility requirements.
Browser Support
This widget supports all modern browsers. Internet Explorer is not supported.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
If you encounter any issues or have questions, please file an issue on the GitHub repository.
We hope you find @emacapt/widget-react helpful in your projects. Happy coding!