Fomu
Fomu (from japanese: フォーム fōmu) is a small library that handles forms in react. Its main qualities are:
- Validation with error messages (async and with possibilty to cancel it!)
- Generates JSON for submit or anything else (by abstract components like Scope, Array!)
- Handling form submission (canceling previous submitting if there is!)
⚠️ Status
️Currently under construction:
- Document the code and create docs
- Optimization (useMemo, useCallback, etc)
Example
import { Fomu, Form, Scope, ArrayField, Input, Checkbox, useFomu } from "fomu"
import api from "./my_api"
const Example = (props) => {
const item = {
name: "Playstation 4",
markets: ["ES", "JP"],
}
const markets = ["US", "ES", "JP"]
/**
* reset the form to initial values
* @param {FormContext<any>} form - fomu's context
*/
const onReset = (form) => (e) => {
e.preventDefault()
form.handleReset()
}
/**
* cancel all! (validations, submit, etc)
* @param {FormContext<any>} form - fomu's context
*/
const onCancel = (form) => (e) => {
e.preventDefault()
form.handleReset()
}
const ctx = useFomu({
id: "formId",
onSubmit: () => {
// the json generated from Fomu would be:
// {
// name: "Playstation 4",
// markets: ["US", "ES", "UK", "FR", "JP", "DE", "IT"],
// _data: {id: "3242621"}
// }
api(ctx.json())
},
})
return (
<Fomu ctx={ctx}>
<Form method="post">
{/* it will generate by json() method -> name: "Playstation 4" */}
<Input
id="name"
path="name"
type="string"
value={item.name}
initialValue={item.name}
placeholder="Playstation 4"
validations={{ required: true }}
/>
{props.errors.name && <span>error! {props.errors.name}</span>}
{/* it will generate by json() method -> markets: ["ES", "JP"] */}
<ArrayField id="markets" path="markets" validations={{ required: true }}>
{markets.map((market) => (
<Checkbox
id={market}
path=""
value={market}
initialChecked={item.some((d) => d == market)}
validEmptyValue
/>
))}
</ArrayField>
{props.errors.markets && <span>error! {props.errors.markets}</span>}
{/* it will generate by json() method -> {_data: {id: "3242621"}} */}
<Input id="id" path="_data.id" type="hidden" value="3242621" initialValue="3242621" />
{/* the input "submit" is handled by fomu */}
<input type="submit" value="Publicar" />
<a href="" onClick={onReset(fomu)}>
RESET
</a>
<a href="" onClick={onCancel(fomu)}>
CANCEL
</a>
{/* functionality/info debug like "is submitting", cancel o reset form */}
<FomuDebugger />
<div>is submitting?: {props.isSubmitting ? "yes" : "no"}</div>
<div>is validating?: {props.isValidating ? "yes" : "no"}</div>
<div>is validated?: {props.isValidated ? "yes" : "no"}</div>
</Form>
</Fomu>
)
}