### Install @avinlab/form using npm
Source: https://github.com/avin/avinlab-form/blob/master/packages/form/README.md
This command installs the @avinlab/form package using npm. Ensure you have Node.js and npm installed on your system.
```sh
npm install @avinlab/form
```
--------------------------------
### Install @avinlab/react-form using npm
Source: https://github.com/avin/avinlab-form/blob/master/packages/react-form/README.md
Installs the @avinlab/react-form library into your project using npm. This is the initial step before using the library's features.
```sh
npm install @avinlab/react-form
```
--------------------------------
### React: Create Controlled Components Faster with createFormComponent
Source: https://github.com/avin/avinlab-form/blob/master/packages/react-form/README.md
Shows how to use the `createFormComponent` helper from @avinlab/react-form to quickly bind form fields to form state. This example defines reusable `FormTextInput` and `FormCheckboxInput` components, demonstrating faster creation of controlled components for forms.
```jsx
import { createFormComponent, useForm } from '@avinlab/react-form';
const TextInput = ({ label, ...props }) => (
);
const FormTextInput = createFormComponent(TextInput, {
getValue: (event) => event.currentTarget.value,
});
const CheckboxInput = ({ label, ...props }) => (
);
const FormCheckboxInput = createFormComponent(CheckboxInput, {
valueAttrName: 'checked',
getValue: (event) => event.target.checked,
});
export function ProfileForm() {
const form = useForm({ email: '', accepted: false });
return (
);
}
```
--------------------------------
### Create Form Component with @avinlab/react-form
Source: https://context7.com/avin/avinlab-form/llms.txt
This snippet demonstrates how to create form-bound versions of base UI components using `createFormComponent` from `@avinlab/react-form`. It includes examples for text inputs, select inputs, and checkboxes, showing how to configure value extraction and attribute names.
```tsx
import React from 'react';
import { useForm, useFormWatch, createFormComponent } from '@avinlab/react-form';
// Base UI components
const TextInput = ({ label, error, ...props }) => (
);
const CheckboxInput = ({ label, ...props }) => (
);
// Create form-bound components
const FormTextInput = createFormComponent(TextInput, {
getValue: (e) => e.currentTarget.value,
});
const FormSelectInput = createFormComponent(SelectInput, {
getValue: (e) => e.currentTarget.value,
});
const FormCheckboxInput = createFormComponent(CheckboxInput, {
valueAttrName: 'checked',
getValue: (e) => e.target.checked,
});
// Usage in a form
function UserProfileForm() {
const form = useForm({
username: '',
email: '',
country: 'us',
newsletter: false,
notifications: true
});
const formValues = useFormWatch(form);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log('Submitted:', form.values);
alert(JSON.stringify(form.values, null, 2));
};
const countryOptions = [
{ value: 'us', label: 'United States' },
{ value: 'uk', label: 'United Kingdom' },
{ value: 'ca', label: 'Canada' },
{ value: 'au', label: 'Australia' },
];
return (
);
}
export default UserProfileForm;
```
--------------------------------
### React Form with Validation using Hooks
Source: https://github.com/avin/avinlab-form/blob/master/packages/react-form/README.md
Demonstrates how to create a form in React using @avinlab/react-form hooks. It includes state management with `useForm`, validation logic with `useFormValidation`, and form submission handling. The example shows input fields for name and age, with basic validation rules.
```jsx
import React from 'react';
import { useForm, useFormValidation, useFormWatch } from '@avinlab/react-form';
const ExampleForm = () => {
const form = useForm({ name: 'Bob', age: 20 });
const { errors, isValid, validate } = useFormValidation(form, (values, prevValues) => {
const errors = {};
if (!values.name) {
errors.name = 'Name is required';
}
if (values.age && values.age < 18) {
errors.age = 'Must be at least 18';
}
return errors;
});
const handleSubmit = (e) => {
e.preventDefault();
if (isValid) {
console.log(form.values);
}
};
// If you want to render the form values:
// const nameValue = useFormWatch(form, 'name');
// const formValuesObj = useFormWatch(form);
return (
);
};
```
--------------------------------
### Configure ESLint for Type-Aware Linting in React/TypeScript
Source: https://github.com/avin/avinlab-form/blob/master/examples/react/README.md
This configuration snippet demonstrates how to set up ESLint for type-aware linting in a React and TypeScript project using Vite. It involves configuring parser options to include TypeScript project files and extending recommended or strict type-checked rules from the @typescript-eslint plugin, along with React-specific rules.
```javascript
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
}
```
--------------------------------
### useFormWatch: Watch All Form Values in React
Source: https://context7.com/avin/avinlab-form/llms.txt
This example shows how to use the useFormWatch hook to subscribe to all form values simultaneously in a React component. It displays the entire form state as a JSON string in a preformatted text block, which updates in real-time as the input fields change. Dependencies include React and the useForm and useFormWatch hooks from '@avinlab/react-form'. It takes a form instance as input and returns an object containing all current form values.
```tsx
// Example of watching entire form
function FormDebugger() {
const form = useForm({
field1: 'value1',
field2: 'value2',
field3: 42
});
// Watch all form values
const allValues = useFormWatch(form);
return (
);
}
export { FormDebugger };
```
--------------------------------
### useFormWatch: Watch Specific Form Fields in React
Source: https://context7.com/avin/avinlab-form/llms.txt
This example demonstrates how to use the useFormWatch hook to subscribe to individual form field changes in a React component. It watches 'price', 'quantity', and 'taxRate' to dynamically calculate and display the subtotal, tax, and total cost. Dependencies include React and the useForm and useFormWatch hooks from '@avinlab/react-form'. It takes a form instance and field names as input and returns the current value of the watched field.
```tsx
import React from 'react';
import { useForm, useFormWatch } from '@avinlab/react-form';
function ProductForm() {
const form = useForm({
productName: '',
price: 0,
quantity: 1,
taxRate: 0.1
});
// Watch specific fields
const price = useFormWatch(form, 'price');
const quantity = useFormWatch(form, 'quantity');
const taxRate = useFormWatch(form, 'taxRate');
// Calculate total (re-calculates when watched fields change)
const subtotal = price * quantity;
const tax = subtotal * taxRate;
const total = subtotal + tax;
return (
);
}
export { ProductForm };
```
--------------------------------
### Create and Manage Form Values with @avinlab/form (JavaScript)
Source: https://github.com/avin/avinlab-form/blob/master/packages/form/README.md
Demonstrates how to create a form instance, subscribe to value updates (both for the entire form and individual fields), set specific values, and unsubscribe from updates using the @avinlab/form library.
```javascript
import { createForm } from '@avinlab/form';
// Create a form with initial values
const initialValues = { name: 'John', age: 30 };
const form = createForm(initialValues);
// Subscribe to updates
const handleUpdateForm = (newValues, prevValues) => {
console.log('Form updated', { newValues, prevValues });
};
form.onUpdate(handleUpdateForm);
const handleUpdateAgeField = (newValue, oldValue) => {
console.log('Field "age" updated', { newValue, oldValue });
};
form.onUpdateField('age', handleUpdateAgeField);
// Set form values
form.setValue('name', 'Jane');
form.setValue('age', 31);
// Set all form values at once
form.setValues({ name: 'Jane', age: 31 });
// Unsubscribe from updates
form.offUpdate(handleUpdateForm);
form.offUpdateField('age', handleUpdateAgeField);
```
--------------------------------
### Create and Manage Form State with @avinlab/form
Source: https://context7.com/avin/avinlab-form/llms.txt
Demonstrates how to create a form instance using `createForm` from the @avinlab/form library. It covers subscribing to form updates, updating single or multiple fields, accessing current and previous values, and unsubscribing from events. This function is framework-agnostic.
```javascript
import { createForm } from '@avinlab/form';
// Create a form with initial values
const form = createForm({
name: 'John',
email: 'john@example.com',
age: 30
});
// Subscribe to all form updates
const handleFormUpdate = (newValues, prevValues) => {
console.log('Form changed:', { newValues, prevValues });
};
form.onUpdate(handleFormUpdate);
// Subscribe to specific field updates
const handleNameUpdate = (newValue, oldValue) => {
console.log('Name changed from', oldValue, 'to', newValue);
};
form.onUpdateField('name', handleNameUpdate);
// Update a single field
form.setValue('name', 'Jane');
// Output: "Name changed from John to Jane"
// Output: "Form changed: {newValues: {name: 'Jane', email: 'john@example.com', age: 30}, ...}"
// Update multiple fields at once
form.setValues({
name: 'Bob',
email: 'bob@example.com',
age: 25
});
// Access current values
console.log(form.values);
// Output: { name: 'Bob', email: 'bob@example.com', age: 25 }
// Access previous values
console.log(form.prevValues);
// Output: { name: 'Jane', email: 'john@example.com', age: 30 }
// Unsubscribe from updates
form.offUpdate(handleFormUpdate);
form.offUpdateField('name', handleNameUpdate);
```
--------------------------------
### Implement Form Validation with @avinlab/form
Source: https://context7.com/avin/avinlab-form/llms.txt
Shows how to use `createFormValidation` to manage validation for a form instance created by `createForm`. It includes setting up a validation function, subscribing to validation changes, and manually triggering validation. Validation runs automatically on form value updates. This functionality is part of the framework-agnostic @avinlab/form package.
```javascript
import { createForm, createFormValidation } from '@avinlab/form';
// Create form
const form = createForm({
username: '',
password: '',
age: 0
});
// Create validation with validation function
const formValidation = createFormValidation(form, (values, prevValues) => {
const errors = {};
if (!values.username) {
errors.username = 'Username is required';
} else if (values.username.length < 3) {
errors.username = 'Username must be at least 3 characters';
}
if (!values.password) {
errors.password = 'Password is required';
} else if (values.password.length < 8) {
errors.password = 'Password must be at least 8 characters';
}
if (values.age < 18) {
errors.age = 'Must be at least 18 years old';
}
return errors;
});
// Check initial validation state
console.log(formValidation.errors);
// Output: { username: 'Username is required', password: 'Password is required', age: 'Must be at least 18 years old' }
console.log(formValidation.isValid);
// Output: false
// Subscribe to validation changes
const handleValidate = (errors) => {
console.log('Validation errors:', errors);
};
formValidation.onValidate(handleValidate);
// Update form values - validation runs automatically
form.setValue('username', 'ab');
// Output: "Validation errors: { username: 'Username must be at least 3 characters', password: 'Password is required', age: 'Must be at least 18 years old' }"
form.setValue('username', 'john_doe');
// Output: "Validation errors: { password: 'Password is required', age: 'Must be at least 18 years old' }"
form.setValue('password', 'securepass123');
form.setValue('age', 25);
// Output: "Validation errors: {}"
console.log(formValidation.isValid);
// Output: true
// Manually trigger validation
formValidation.validate();
// Update validation logic dynamically
formValidation.setValidation((values) => {
const errors = {};
if (values.username.length < 5) {
errors.username = 'Username must be at least 5 characters';
}
return errors;
});
// Unsubscribe
formValidation.offValidate(handleValidate);
```
--------------------------------
### Form Validation with @avinlab/form (JavaScript)
Source: https://github.com/avin/avinlab-form/blob/master/packages/form/README.md
Illustrates how to set up form validation using `createFormValidation`. It shows how to define validation rules, access validation errors and validity status, and subscribe to validation changes. Validation can be triggered automatically on value changes or manually.
```javascript
import { createForm, createFormValidation } from '@avinlab/form';
const initialValues = { name: 'John', age: 30 };
const form = createForm(initialValues);
const formValidation = createFormValidation(form, (values) => {
const errors = {};
if (!values.name) {
errors.name = 'Name is required';
}
if (values.age && values.age < 18) {
errors.age = 'Must be at least 18';
}
return errors;
});
console.log(formValidation.errors); // Output: {}
console.log(formValidation.isValid); // Output: true
// Set an incorrect value for the age field
form.setValue('age', 15);
console.log(formValidation.errors); // Output: {age: 'Must be at least 18'}
console.log(formValidation.isValid); // Output: false
// Subscribe to validation changes
const handler = (errors) => {
console.log(errors);
};
formValidation.onValidate(handler);
// Unsubscribe from validation updates
formValidation.offValidate(handler);
// Validation is triggered automatically when the form values change,
// but you can also initiate validation manually
formValidation.validate();
```
--------------------------------
### useForm Hook - React Form Initialization and Usage
Source: https://context7.com/avin/avinlab-form/llms.txt
Demonstrates how to initialize the `useForm` hook with default values and use it to manage form state, including handling input changes and form submission. It takes an object of initial form values and returns a `form` object with `values` and `setValue` properties.
```tsx
import React from 'react';
import { useForm } from '@avinlab/react-form';
function RegistrationForm() {
// Create form with initial values
const form = useForm({
firstName: '',
lastName: '',
email: '',
subscribe: false
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log('Submitted values:', form.values);
// Output: { firstName: '...', lastName: '...', email: '...', subscribe: true/false }
};
return (
);
}
export default RegistrationForm;
```
--------------------------------
### Implement React Form Validation with useFormValidation
Source: https://context7.com/avin/avinlab-form/llms.txt
This React hook manages form validation state and triggers component re-renders when the validation status changes. It requires the useForm hook and is designed for use within React functional components. It takes the form state and a validation function as arguments, returning the validation errors and validity status.
```tsx
import React, { useState } from 'react';
import { useForm, useFormValidation } from '@avinlab/react-form';
interface LoginFormValues {
email: string;
password: string;
}
interface LoginFormErrors {
email?: string;
password?: string;
}
function LoginForm() {
const [isSubmitted, setIsSubmitted] = useState(false);
const form = useForm({
email: '',
password: ''
});
const { errors, isValid } = useFormValidation(
form,
(values) => {
const errors: LoginFormErrors = {};
if (!values.email) {
errors.email = 'Email is required';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
errors.email = 'Invalid email format';
}
if (!values.password) {
errors.password = 'Password is required';
} else if (values.password.length < 6) {
errors.password = 'Password must be at least 6 characters';
}
return errors;
}
);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitted(true);
if (isValid) {
console.log('Login with:', form.values);
// Make API call here
alert(`Logging in as ${form.values.email}`);
} else {
console.log('Form has errors:', errors);
}
};
return (
);
}
export default LoginForm;
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.