npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@developer-hub/react-reusable-form

v1.2.1

Published

A reusable, dynamic form component built with React Hook Form and Yup

Readme

React Reusable Form Component

A dynamic and reusable form component built with react-hook-form and validated using Yup. This component accepts a field configuration array, a Yup validation schema, and a callback function for form submission.

Installation

npm i @developer-hub/react-reusable-form @hookform/resolvers yup

Note: This component requires react-hook-form, @hookform/resolvers, and yup as peer dependencies.

Basic Usage

import { useRef } from 'react';
import ReusableForm from '@developer-hub/react-reusable-form';
import { formSchema } from './schema';

const MyComponent = () => {
  const formRef = useRef();

  const handleSubmit = (data) => {
    console.log('Form data:', data);
    // Reset form after successful submission
    formRef.current?.reset();
  };

  const handleReset = () => {
    // Reset form manually
    formRef.current?.reset();
  };

  return (
    <div>
      <ReusableForm
        fields={yourFields}
        schema={formSchema}
        onSubmit={handleSubmit}
        formRef={formRef}
      />
      <button onClick={handleReset}>Clear Form</button>
    </div>
  );
};

Form Reset Functionality

The component provides a powerful reset method through the formRef prop that allows you to programmatically reset the form state.

Setting Up Form Reset

  1. Create a ref: Use useRef() to create a reference
  2. Pass the ref: Provide it to the formRef prop
  3. Call reset: Use formRef.current?.reset() to reset the form
import { useRef } from 'react';

const MyComponent = () => {
  const formRef = useRef();

  // Reset after successful submission
  const handleSubmit = (data) => {
    // Process your data
    console.log('Form data:', data);
    
    // Reset form to initial state
    formRef.current?.reset();
  };

  // Reset manually with a button
  const clearForm = () => {
    formRef.current?.reset();
  };

  return (
    <>
      <ReusableForm
        fields={fields}
        schema={schema}
        onSubmit={handleSubmit}
        formRef={formRef}
      />
      <button type="button" onClick={clearForm}>
        Clear Form
      </button>
    </>
  );
};

Reset Method Features

  • Complete reset: Clears all form fields and resets them to their initial values
  • Validation reset: Clears any validation errors
  • State reset: Resets the entire form state managed by react-hook-form
  • Safe usage: Uses optional chaining (?.) to prevent errors if ref is not available

Common Reset Patterns

// Reset after successful API call
const handleSubmit = async (data) => {
  try {
    await submitToAPI(data);
    formRef.current?.reset(); // Reset on success
  } catch (error) {
    console.error('Submission failed:', error);
    // Don't reset on error
  }
};

// Reset with confirmation
const handleReset = () => {
  if (window.confirm('Are you sure you want to clear the form?')) {
    formRef.current?.reset();
  }
};

// Reset specific sections (if needed)
const resetForm = () => {
  formRef.current?.reset();
  // Additional custom reset logic if needed
};

Field Configuration

Form fields are defined using the fields prop, which accepts an array of field objects:

Basic Field Structure

All fields support the following basic properties:

{
  name: "email",           // Required: Field identifier
  label: "Email Address",  // Required: Display label
  type: "email",           // Required: Field type
  placeholder: "Enter your email" // Optional: Placeholder text
}

Supported Field Types

  • text - Text input
  • email - Email input
  • password - Password input
  • date - Date input
  • textarea - Text area
  • checkbox - Checkbox
  • radio - Radio buttons
  • select - Select dropdown
  • file - File upload
  • rating - Interactive star rating component

Fields with Options (Radio & Select)

{
  name: "gender",
  label: "Gender",
  type: "radio", // or "select"
  options: [
    { value: "male", label: "Male" },
    { value: "female", label: "Female" },
    { value: "other", label: "Other" }
  ]
}

Conditional Fields

{
  name: "customCountry",
  label: "Specify Country",
  type: "text",
  conditional: {
    field: "country",
    value: "other"
  }
}

Rating Fields

{
  name: "rating",
  label: "Rate your experience",
  type: "rating",
  max: 5
}

Validation Schema

import * as yup from "yup";

export const formSchema = yup.object().shape({
  email: yup
    .string()
    .email("Please enter a valid email")
    .required("Email is required"),

  rating: yup
    .number()
    .min(1, "Please provide a rating")
    .max(5, "Rating cannot exceed 5 stars")
    .required("Rating is required"),

  customCountry: yup
    .string()
    .when("country", {
      is: "other",
      then: (schema) => schema.required("Please specify your country"),
      otherwise: (schema) => schema.notRequired()
    })
});

Props Reference

Core Props

| Prop | Type | Required | Description | |------|------|----------|-------------| | fields | Array | Yes | Array of field configuration objects | | schema | Yup Schema | Yes | Yup validation schema | | onSubmit | Function | Yes | Callback function for form submission | | formRef | Ref | No | Reference to access form methods like reset() |

Styling Props

Use the className props to customize every part of the form:

<ReusableForm
  fields={fields}
  schema={schema}
  onSubmit={handleSubmit}
  formRef={formRef}
  className="..."
  inputClassName="..."
  labelClassName="..."
  selectClassName="..."
  textareaClassName="..."
  checkboxClassName="..."
  checkboxInputClassName="..."
  radioWrapperClassName="..."
  fileInputClassName="..."
  ratingClassName="..."
  submitButtonClassName="..."
/>

License

MIT License © developer-hub

Buy me a coffee ☕