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 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-generic-forms

v1.0.1

Published

Use typesafe forms for your react apps. This library is heavily inspired by [Formik](https://jaredpalmer.com/formik), but from the beginning with typescript in mind.

Downloads

2

Readme

react-generic-forms

Use typesafe forms for your react apps.
This library is heavily inspired by Formik, but from the beginning with typescript in mind.

How it works

  1. You have to define all the fields for your form (optional with validators) and its initial values
  2. The form accepts a function as child, which will pass all fields and an isSubmitting property
  3. All input components have to be connected to a specific field. They have to change the field.value property in its onChange event.
  4. A submit button (<input type="submit" />) will trigger the validation and will call the onSubmit handler only if all fields are valid.
  5. Within the onSubmit handler you have access to the original react event, all values and to form actions.

Example

// common.ts

// probably there are some interfaces shared between client and server
interface ISignUpData {
    email: string;
    password: string;
    password2: string;
}
// signup.ts

import * as React from "react";
import { FieldOptions, GenericForm, IGenericFormResult, isSameAs, required, simpleMail } from "react-generic-forms";

import { ISignUpData } from "./common";
import { InputWithValidator } from "./input";

// create the fields
// hint: required() is needless while using any other validator
const fieldOptions: FieldOptions<ISignUpData> = {
    email: { validators: [simpleMail()] }, 
    password: { validators: [required()] },
    password2: { validators: [isSameAs("password")] },
};

// define initial values
const initialValues: ISignUpData = {
    email: "",
    password: "",
    password2: "",
};

// implement submit handler
const handleSubmit = async (result: IGenericFormResult<ISignUpData>) => {
    console.log(result.values);

    result.actions.setSubmitting(false);
};

// implement form component
export const SignUp = () => (
    <GenericForm fieldOptions={fieldOptions} initialValues={initialValues} onSubmit={handleSubmit}>
        {formProps => (
            <>
                <InputWithValidator type="text" field={formProps.fields.email} placeholder="E-Mail" />
                <InputWithValidator type="password" field={formProps.fields.password} placeholder="Password" />
                <InputWithValidator type="password" field={formProps.fields.password2} placeholder="Confirm Password" />

                <input type="submit" value="Register" disabled={formProps.isSubmitting} />
            </>
        )}
    </GenericForm>
);
// input.ts

import * as React from "react";
import { IField } from "react-generic-forms";

interface IInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
    field: IField<any>;
}

// a custom input component which renders validation errors
export const InputWithValidator = ({ field, ...inputProps }: IInputProps) => {
    const style = { borderColor: field.errors.length ? "red" : "gray" };
    const onChange = (event: React.ChangeEvent<HTMLInputElement>) => field.value = event.currentTarget.value;

    return (
        <div>
            <input {...inputProps} defaultValue={field.value} style={style} onChange={onChange} />
            <ul>
                {field.errors.map((error, i) => <li key={i}>{error}</li>)}
            </ul>
        </div>  
    );
};

Custom inputs

As the inputs only have to implement the onChange handler you can use the native html input elements or custom ones like React Select. For this reason, there is no default input component included.

Custom validators

The following types are used to define a custom validator:

  • type ValidationFunction<FieldValueType = any, T = any> = (value: FieldValueType | null | undefined, fields: Fields<T>) => string | null
  • type CustomValidator = (...params: any[]) => ValidationFunction<T, F>

remark:

  • FieldValueType is the type of the field to validate
  • T is the generic type of the form

So to implement your custom validator

  1. create a function with own validator settings
  2. return a function with the current value and optional all fields as parameters
  3. return null, if the field is valid or an error message, if it's not.

example:

// simple validator
const arrayHasLength = (length: number): ValidationFunction<any[]> => {
    return value => {
        if (value && value.length === length) {
            return null;
        }
    
        return `The array should have ${length} items.`;
    };
}

// more complex validator
const numberIsGreaterThanOtherFieldValue = <T>(otherFieldName: keyof T): ValidationFunction<number, T> => {
    return (value, fields) => {
        if(value && value > fields[otherFieldName].value) {
            return null;
        }
        
        return `${value} <= ${fields[otherFieldName].value}`;
    }
}