1.0.0 • Published 7 months ago

react-smartest-form v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
7 months ago

React Smart Form

A React component library for building smart, validated forms with built-in validation using React Hook Form and Yup. Features type-safe components, customizable validation rules, and accessible form elements.

Features

  • 🔒 Built-in validation with Yup schemas
  • 📝 Type-safe form components
  • ♿ Accessible form elements
  • 🎨 Customizable styling
  • 💪 TypeScript support
  • 🔄 Form state management with React Hook Form

Installation

npm install react-smart-form

Quick Start

import { useForm, FormProvider } from 'react-hook-form';
import { Email, Password, TextInput, Select } from 'react-smart-form';

function SignupForm() {
  const methods = useForm();
  
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <TextInput 
          name="username" 
          label="Username"
          required
          minLength={3}
        />
        <Email 
          name="email" 
          label="Email Address"
          required 
        />
        <Password 
          name="password" 
          label="Password"
          showStrengthIndicator
          minLength={8}
        />
        <Select
          name="country"
          label="Country"
          options={[
            { value: 'us', label: 'United States' },
            { value: 'uk', label: 'United Kingdom' }
          ]}
        />
        <button type="submit">Sign Up</button>
      </form>
    </FormProvider>
  );
}

Components

FormWrapper

The main form container that provides form context and validation.

import { FormWrapper } from 'react-smart-form';
import * as yup from 'yup';

const validationSchema = yup.object({
  email: yup.string().email().required(),
  password: yup.string().min(8).required()
});

function LoginForm() {
  const handleSubmit = (data) => {
    console.log('Form submitted:', data);
  };

  return (
    <FormWrapper
      onSubmit={handleSubmit}
      validationSchema={validationSchema}
    >
      {/* Form fields */}
    </FormWrapper>
  );
}

Props

PropTypeDefaultDescription
childrenReactNode | Function-Form content or render function
onSubmitFunction-Form submission handler
validationSchemayup.ObjectSchema-Yup validation schema
defaultValuesobject-Initial form values
modestring'onTouched'Validation mode
resetOnSubmitbooleanfalseClear form after submit
onErrorFunction-Error handling callback
disabledbooleanfalseDisable entire form

TextInput Component

A versatile text input component for general text fields.

// Basic Usage
<TextInput
  name="firstName"
  label="First Name"
  required
/>

// Advanced Usage
<TextInput
  name="username"
  label="Username"
  required
  minLength={3}
  maxLength={20}
  pattern={/^[a-zA-Z0-9_]+$/}
  errorMessage="Username must be alphanumeric"
  placeholder="Enter username"
  type="text"
  autoComplete="username"
  className="custom-input"
/>

Props

  • name (required): Field identifier
  • label: Input label
  • required: Is field required (default: false)
  • minLength: Minimum text length
  • maxLength: Maximum text length
  • pattern: RegExp pattern for validation
  • type: Input type ('text' | 'tel' | 'url' | 'search')
  • errorMessage: Custom validation message
  • placeholder: Input placeholder
  • autoComplete: HTML autocomplete attribute
  • className: Custom CSS class

Password Component

A secure password input with strength indicator and visibility toggle.

// Basic Usage
<Password
  name="password"
  label="Password"
/>

// Advanced Usage
<Password
  name="password"
  label="Password"
  required
  minLength={8}
  maxLength={100}
  showStrengthIndicator
  showTogglePassword
  errorMessage="Password must meet requirements"
  strengthLabels={{
    weak: 'Too Weak',
    medium: 'Good',
    strong: 'Strong'
  }}
/>

Props

PropTypeDefaultDescription
namestring-Field identifier
labelstring-Input label
requiredbooleantrueIs field required
minLengthnumber6Minimum length
maxLengthnumber100Maximum length
showStrengthIndicatorbooleanfalseShow strength meter
showTogglePasswordbooleantrueShow visibility toggle
patternRegExp/^(?=.a-z)(?=.A-Z)(?=.\d).$/Password pattern
errorMessagestring-Custom error message
strengthLabelsobject{ weak: 'Weak', medium: 'Medium', strong: 'Strong' }Custom strength labels

Email Component

An email input with built-in email format validation.

// Basic Usage
<Email
  name="email"
  label="Email"
/>

// Advanced Usage
<Email
  name="email"
  label="Email Address"
  required
  errorMessage="Please enter a valid email"
  placeholder="your@email.com"
  className="custom-email"
/>

Props

PropTypeDefaultDescription
namestring-Field identifier
labelstring-Input label
requiredbooleantrueIs field required
errorMessagestring-Custom error message
placeholderstring'Enter your email'Input placeholder
classNamestring-Custom CSS class

Select Component

A dropdown select component with single/multiple selection support.

// Basic Usage
<Select
  name="country"
  options={[
    { value: 'us', label: 'USA' },
    { value: 'uk', label: 'UK' }
  ]}
/>

// Advanced Usage
<Select
  name="countries"
  label="Countries"
  options={[
    { value: 'us', label: 'United States' },
    { value: 'uk', label: 'United Kingdom' },
    { value: 'ca', label: 'Canada' }
  ]}
  required
  multiple
  placeholder="Select countries"
  defaultValue={['us']}
  className="custom-select"
/>

Props

PropTypeDefaultDescription
namestring-Field identifier
optionsOption[]-Array of option objects
labelstring-Select label
requiredbooleanfalseIs field required
multiplebooleanfalseAllow multiple selections
placeholderstring'Select an option'Placeholder text
defaultValuestring | string[]-Default selected value(s)
classNamestring-Custom CSS class

Styling

The library comes with default styles that can be customized by overriding CSS classes:

/* Override default styles in your app */
.email-field,
.password-field,
.text-input-field,
.select-field {
  margin-bottom: 1rem;
}

.email-input,
.password-input,
.text-input,
.select-input {
  width: 100%;
  padding: 0.625rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
}

.error-message {
  color: #dc2626;
  font-size: 0.75rem;
}

.required-mark {
  color: #dc2626;
  margin-left: 0.25rem;
}

TypeScript Support

import { 
  FormWrapperProps, 
  TextInputProps, 
  PasswordProps, 
  EmailProps, 
  SelectProps 
} from 'react-smart-form';

// Type-safe props
const emailProps: EmailProps = {
  name: 'email',
  required: true,
  label: 'Email Address'
};

Development

# Install dependencies
npm install

# Build the library
npm run build

# Run tests
npm test

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

ISC

Support

For issues and feature requests, please file an issue on GitHub.