• Stars
    star
    213
  • Rank 178,800 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Good Form Library

React Jeff

A Good Form Library

  • ~800 bytes minified+gzip
  • Easy to learn API
  • Write your form code in a way that is reusable and testable
  • Seamless sync and async form validations (including on form submit)
  • Tons of utilty features out of the box
  • Written with React Hooks
  • Typed with TypeScript

Install

npm install react-jeff

Usage

import React from "react"
import { useField, useForm } from "react-jeff"

/**
 * 1. Write some validations that accept an input value and return an array of errors.
 * (If the array is empty, the value is considered valid)
 */

function validateUsername(value) {
	let errs = []
	if (value.length < 3) errs.push("Must be at least 3 characters long")
	if (!/^[a-z0-9_-]*$/i.test(value)) errs.push("Must only contain alphanumeric characters or dashes/underscores")
	if (!/^[a-z0-9]/i.test(value)) errs.push("Must start with alphanumeric character")
	if (!/[a-z0-9]$/i.test(value)) errs.push("Must end with alphanumeric character")
	return errs
}

function validatePassword(value) {
	let errs = []
	if (value.length < 6) errs.push("Must be at least 6 characters long")
	if (!/[a-z]/.test(value)) errs.push("Must contain at least one lowercase letter")
	if (!/[A-Z]/.test(value)) errs.push("Must contain at least one uppercase letter")
	if (!/[0-9]/.test(value)) errs.push("Must contain at least one number")
	return errs
}

/**
 * 2. Write some custom components that you'll reuse for all of your forms.
 */

function Form({ onSubmit, ...props }) {
	return (
		<form {...props} onSubmit={event => {
			event.preventDefault() // Make sure you call `event.preventDefault()` on your forms!
			onSubmit()
		}}/>
	)
}

function Input({ onChange, ...props }) {
	return (
		<input {...props} onChange={event => {
			onChange(event.currentTarget.value) // Make sure all of your inputs call `props.onChange` with the new value.
		}} />
	)
}

/**
 * 3. Create your form!
 */
 
function SignupForm() {
        // Create some fields...
	let username = useField({
		defaultValue: "",
		required: true,
		validations: [validateUsername],
	})

	let password = useField({
		defaultValue: "",
		required: true,
		validations: [validatePassword],
	})
	
	// Create your onSubmit handler...
	function onSubmit() {
		// Do something with the form...
	}
	
	// Create your form...
	let form = useForm({
		fields: [username, password],
		onSubmit: onSubmit,
	})
	
	// Write your UI!
	return (
		<Form {...form.props}>
			<Input type="text" {...username.props} />
			<Input type="password" {...password.props} />
			<button type="submit">Sign Up</button>
		</Form>
	)
}

API

useField()

Call useField() to create a single field in a form.

let field = useField({
	defaultValue: (value), // ....... (Required) The default value of the field.
	validations: [(...errors)], // .. (Optional) Validations to run when the field is `validate()`'d.
	required: boolean, // ........... (Optional) Should the field be required?
	disabled: boolean, // ........... (Optional) Should the field be disabled?
	readOnly: boolean, // ........... (Optional) Should the field be readOnly?
})
field == {
	value: (value), // ......... The current value of the field.
	defaultValue: (value), // .. The `defaultValue` passed into `useField({ defaultValue })`.

	dirty: boolean, // ......... Has the field been changed from its defaultValue?
	touched: boolean, // ....... Has the element this field is attached to been focused previously?
	focused: boolean, // ....... Is the element this field is attached to currently focused?
	blurred: boolean, // ....... Has the element this field is attached to been focused and then blurred?

	validating: boolean, // .... Is the field validating itself?
	valid: boolean, // ......... Is the field currently valid? (must have no errors, and if the field is required, must not be empty)
	errors: [(...errors)], // .. The collected errors returned by `opts.validations`

	required: boolean, // ...... Is the field required?
	disabled: boolean, // ...... Is the field disabled?
	readOnly: boolean, // ...... Is the field readOnly?

	setValue: Function, // ..... Call with a value to manually update the value of the field.
	setRequired: Function, // .. Call with true/false to manually set the `required` state of the field.
	setDisabled: Function, // .. Call with true/false to manually set the `disabled` state of the field.
	setReadOnly: Function, // .. Call with true/false to manually set the `readOnly` state of the field.

	reset: Function, // ........ Reset the field to its default state.
	validate: Function, // ..... Manually tell the field to validate itself (updating other fields).

	// Props to pass into an component to attach the `field` to it:
	props: {
		value: (value), // ....... The current value (matches `field.value`).

		onChange: Function, // ... An `onChange` handler to update the value of the field.
		onFocus: Function, // .... An `onFocus` handler to update the focused/touched/blurred states of the field.
		onBlur: Function, // ..... An `onFocus` handler to update the focused/blurred states of the field.

		required: boolean, // .... Should the element be `required`?
		disabled: boolean, // .... Should the element be `disabled`?
		readOnly: boolean, // .... Should the element be `readOnly`?
	},
}

useForm()

Call useForm() with to create a single form.

let form = useForm({
	fields: [(...fields)], // .. All of the fields created via `useField()` that are part of the form.
	onSubmit: Function, // ..... A submit handler for the form that receives the form submit event.
})
form == {
	fieldErrors: [(...errors)], // ... The collected errors from all of the fields in the form.
	submitErrors: [(...errors)], // .. The errors returned by `opts.onSubmit`.

	submitted: boolean, // ........... Has the form been submitted at any point?
	submitting: boolean, // .......... Is the form currently submitting?

	focused: boolean, // ............. Are *any* of the fields in the form currently `focused`?
	touched: boolean, // ............. Are *any* of the fields in the form currently `touched`?
	dirty: boolean, // ............... Are *any* of the fields in the form currently `dirty`?
	valid: boolean, // ............... Are *all* of the fields in the form currently `valid`?
	validating: boolean, // .......... Are *any* of the fields in the form currently `validating`?

	reset: Function, // .............. Reset all of the fields in the form.
	validate: Function, // ........... Validate all of the fields in the form.
	submit: Function, // ............. Submit the form manually.

	// Props to pass into a form component to attach the `form` to it:
	props: {
		onSubmit: Function, // ......... An onSubmit handler to pass to an element that submits the form.
	},
}

More Repositories

1

the-super-tiny-compiler

โ›„ Possibly the smallest compiler ever
JavaScript
25,786
star
2

react-loadable

โณ A higher order component for loading components with promises.
JavaScript
16,596
star
3

babel-handbook

๐Ÿ“˜ A guided handbook on how to use Babel and how to create plugins for Babel.
11,881
star
4

itsy-bitsy-data-structures

๐Ÿฐ All the things you didn't know you wanted to know about data structures
JavaScript
8,574
star
5

unstated

State so simple, it goes without saying
JavaScript
7,821
star
6

spectacle-code-slide

๐Ÿค˜ Present code with style
JavaScript
4,170
star
7

unstated-next

200 bytes to never think about React state management libraries ever again
TypeScript
4,092
star
8

tinykeys

A tiny (~400 B) & modern library for keybindings.
HTML
3,362
star
9

babel-react-optimize

๐Ÿš€ A Babel preset and plugins for optimizing React code.
JavaScript
1,680
star
10

tailwindcss-animate

A Tailwind CSS plugin for creating beautiful animations
JavaScript
1,084
star
11

glow

Make your Flow errors GLOW
JavaScript
699
star
12

create-react-context

Polyfill for the proposed React context API
JavaScript
695
star
13

json-parser-in-typescript-very-bad-idea-please-dont-use

JSON Parser written entirely in TypeScript's type system
TypeScript
424
star
14

react-gridlist

A virtual-scrolling GridList component based on CSS Grids
TypeScript
421
star
15

favorite-software

๐ŸŒŸ Best software for developers and power users.
355
star
16

marionette-wires

:shipit: An opinionated example application built with Marionette.js.
JavaScript
325
star
17

pretty-format

โœจ Stringify any JavaScript value
304
star
18

ghost-lang

๐Ÿ‘ป A friendly little language for you and me.
300
star
19

documentation-handbook

How to write high-quality friendly documentation that people want to read.
268
star
20

roast-my-deps

Your dependencies are bad and you should feel bad
JavaScript
265
star
21

bey

Simple immutable state for React using Immer
JavaScript
260
star
22

tickedoff

Tiny library (<200B gzip) for deferring something by a "tick"
JavaScript
217
star
23

react-performance-observer

Get performance measurements from React Fiber
JavaScript
210
star
24

gender-regex

Regex to test for valid genders
JavaScript
193
star
25

anti-fascist-mit-license

MIT license with additional text to prohibit use by fascists
187
star
26

purposefile

Make sure every file in your repo is exactly where it should be
TypeScript
168
star
27

react-loadable-example

Example project for React Loadable
JavaScript
149
star
28

bootcamp

๐Ÿ‘ข Jasmine-style BDD testing written in Sass for Sass.
CSS
141
star
29

write-files-atomic

Write many files atomically
JavaScript
124
star
30

sarcastic

Cast unknown values to typed values
JavaScript
98
star
31

ninos

Simple stubbing/spying for AVA
JavaScript
96
star
32

repo-growth

Measure how fast your repo is growing using cloc
JavaScript
89
star
33

workspaces-run

Run tasks/scripts across Yarn/Lerna/Bolt/etc workspaces.
TypeScript
88
star
34

license

The MIT license (with personal exceptions)
86
star
35

scritch

A small CLI to help you write sharable scripts for your team
JavaScript
84
star
36

react-markers

Add markers to your React components for easy testing with actual DOM elements
JavaScript
80
star
37

assert-equal-jsx

assertEqualJSX
JavaScript
78
star
38

proposal-promise-prototype-inspect

Proposal for Promise.prototype.inspect
JavaScript
78
star
39

globby-cli

User-friendly glob matching CLI
JavaScript
76
star
40

spawndamnit

Take care of your spawn()
JavaScript
76
star
41

grob

grep, but in JavaScript... I've truly outdone myself.
JavaScript
72
star
42

react-required-if

React PropType to conditionally add `.isRequired` based on other props
JavaScript
71
star
43

havetheybeenpwned

Test if your user's password has been pwned using the haveibeenpwned.com API
JavaScript
69
star
44

react-prop-matrix

Render something using every possible combination of props
JavaScript
68
star
45

renderator

JavaScript
65
star
46

dark-mode-github-readme-logos

How to make logos in your README that support GitHub's new dark mode
64
star
47

reduxxx

Redux, explicit.
TypeScript
64
star
48

babel-plugin-react-pure-components

Optimize React code by making pure classes into functions
JavaScript
61
star
49

react-test-renderer

[DEPRECATED] A lightweight solution to testing fully-rendered React Components
JavaScript
58
star
50

fixturez

Easily create and maintain test fixtures in the file system
JavaScript
58
star
51

ballistic

๐Ÿ”จ Utility-Belt Library for Sass
CSS
56
star
52

enable-npm-2fa

A script for enabling 2FA on all of your npm packages
JavaScript
55
star
53

cirbuf

A tiny and fast circular buffer
TypeScript
53
star
54

VisibilityObserver

Experimental API for observing the visible box of an element
TypeScript
51
star
55

dependency-free

An experiment to unify/speed up CI/local development via small Docker containers
TypeScript
49
star
56

naw

Your very own containerized build system!
TypeScript
47
star
57

react-stylish

๐ŸŽ€ Make your React component style-able by all
JavaScript
47
star
58

tested-components

Browser integration testing utils for styled-components
JavaScript
41
star
59

jamie.build

the website
HTML
41
star
60

codeowners-enforcer

Enforce CODEOWNERS files on your repo
Rust
41
star
61

std-pkg

The Official package.json Standardโ„ข for Npmยฎ endorsed fields
JavaScript
41
star
62

babel-plugin-private-underscores

Make _classMembers 'private' using symbols
JavaScript
39
star
63

userscript-github-disable-turbolinks

A userscript to disable GitHub turbolinks to force full page navigations
JavaScript
39
star
64

git-workflow

Git workflow for teams
38
star
65

pride

๐Ÿ‘ฌ PrideJS logo
38
star
66

babel-plugin-import-inspector

Babel plugin to report dynamic imports with import-inspector with metadata about the import
JavaScript
38
star
67

revalid

Composable validators
JavaScript
37
star
68

ci-parallel-vars

Get CI environment variables for parallelizing builds
JavaScript
37
star
69

crowdin-sync

๐ŸŒ How to setup Crowdin to sync with GitHub
Ruby
37
star
70

incremental-dom-react-helper

Helper to make Google's incremental-dom library work with React's compile target today.
JavaScript
36
star
71

guarded-string

Prevent accidentally introducing XSS holes with the strings in your app
JavaScript
36
star
72

babel-plugin-hash-strings

Replace all instances of "@@strings like this" with hashes.
JavaScript
35
star
73

react-module-experiment

JavaScript
34
star
74

task-graph-runner

Run async tasks with dependencies
JavaScript
34
star
75

json-peek

Stringify JSON *just enough* to see what it is
JavaScript
33
star
76

babel-plugin-ken-wheeler

Code like you dope
JavaScript
33
star
77

how-to-build-a-compiler

How to build a compiler โ€“ย THE TALK
HTML
33
star
78

js-memory-heap-profiling

JavaScript
32
star
79

backbone.service

A simple service class for Backbone.
JavaScript
31
star
80

dep-size-inspect

JavaScript
29
star
81

pffffff

pfffffffffffffffffffff whatever
JavaScript
28
star
82

shimiteer

Puppeteer API shim for other browsers using WebdriverIO
JavaScript
27
star
83

better-directory-sort

Improved sorting order for directory entities
JavaScript
27
star
84

isolated-core-demo

JavaScript
27
star
85

graph-sequencer

Sort items in a graph using a topological sort while resolving cycles with priority groups
JavaScript
27
star
86

import-inspector

Wrap dynamic imports with metadata about the import
JavaScript
26
star
87

backbone-routing

Simple router and route classes for Backbone.
JavaScript
26
star
88

flow-shut-up

Add inline Flow comments to make Flow shut up about errors
JavaScript
25
star
89

proposal-promise-settle

This repository is a work in progress and not seeking feedback yet.
JavaScript
22
star
90

tumblr-downloader

Download all your female-presenting nipples from Tumblr
JavaScript
22
star
91

backbone.storage

A simple storage class for Backbone Models and Collections.
JavaScript
22
star
92

parcel-rust-example

Example of using Rust code in Parcel
HTML
22
star
93

temperment

Get a random temporary file or directory path that will delete itself
JavaScript
22
star
94

is-mergeable

Check if a GitHub Pull Request is in a (most likely) mergeable state
JavaScript
22
star
95

gud

Create a 'gud nuff' (not cryptographically secure) globally unique id
JavaScript
21
star
96

min-indent

Get the shortest leading whitespace from lines in a string
JavaScript
20
star
97

babel-setup-react-transform

Example Babel project using babel-plugin-react-transform
JavaScript
20
star
98

codeowners-utils

Utilities for working with CODEOWNERS files
TypeScript
19
star
99

my-react

Ideas for React APIs
JavaScript
18
star
100

LibManUal

Shell
18
star