Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/synvox/use-fields
Easy state management for forms
https://github.com/synvox/use-fields
Last synced: 2 months ago
JSON representation
Easy state management for forms
- Host: GitHub
- URL: https://github.com/synvox/use-fields
- Owner: Synvox
- Created: 2019-05-06T19:16:18.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-03T21:26:38.000Z (almost 2 years ago)
- Last Synced: 2024-04-28T07:25:39.489Z (8 months ago)
- Language: JavaScript
- Size: 782 KB
- Stars: 4
- Watchers: 3
- Forks: 0
- Open Issues: 13
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# `use-fields`
[![codecov](https://img.shields.io/travis/Synvox/use-fields.svg)](https://travis-ci.org/Synvox/use-fields)
[![codecov](https://codecov.io/gh/Synvox/use-fields/branch/master/graph/badge.svg)](https://codecov.io/gh/Synvox/use-fields)```
npm i use-fields
```This is a lightweight state management system for composable forms.
Use like this:```js
const { field, value, touched } = useFields({ initialValue: { name: "blah" } });
```and
```js
```
or the `field` function returns a object with the shape:
```js
{
value: T
onChange: function T | Event>
}
```useFields can be used to build big/flexible forms. To work on a nested property,
you must nest components too. I've debated making this easy by changing fields to
accept a path, but decided against it because you probably should be building a
child component at that point. ;)This also comes with an `input` Higher Order Function. This function takes a
function component and `memo`s the function component as well as allows a
`defaultValue` prop to be passed creating an uncontrolled input.Notice it is _always_ onChange and value, not onClick and checked (for checkbox).
Wrap these types of components with `input` and a function to map these
props together:```js
const Checkbox = input(function Checkbox({ value: checked, onChange }) {
return (
onChange(!checked)}
/>
);
});
```It is recommended to use useFields within these input functions where needed:
```js
const { field } = useFields({ value, onChange });
```which allows you to build data trees that are from separate components.
## Usage:
```js
import React from "react";
import { useFields, input } from "use-fields";const ToggleBox = input(({ value, onChange, ...props }, ref) => {
return (
onChange(!value)} {...props} ref={ref}>
{value ? "on" : "off"}
);
});function LoginForm() {
const { field, value } = useFields({
initialValue: {
username: "",
password: "",
rememberMe: false
}
// or pass value and onChange
});function submit(e) {
e.preventDefault();
// do something with value:
// {username: '', password: ''}
}return (
Username:
Password:
Remember Me:
Log In
);
}
```## License
MIT