React form with Custom Input

Description

When we work with react, sometimes we need a custom element to provide advanced interaction with users, like a custom date input, custom select field or a tag creator, for all these cases we can use many options of components provided by the community. But these custom elements cannot simulate de same events as a native element, for this reason, useForm cannot provide the same experience what useForm provide with a native element like <input>, but we can use useForm to manage this kind of component like a controlled element.

Custom inputs receive generics properties, onChange, value, and property to simulate onBlur event. When you use a custom input every change that happened in the input state is replied in state of form component because this we cannot use fell the uncontrolled inputs in custom elements.

Usage

useForm provides a custom function, this function as a link with input and a object property of form state.

Use dot notation to create advanced objects or to map object values. Type an entry name and type or an entry property object.

import { useForm } from "@use-form/use-form";
import Select from "react-select";
import DatePicker from "react-datepicker";
const initialValues = {
candies: {
iceCream: [{ value: "chocolate", label: "Chocolate" }],
},
date: new Date("05/26/2020"),
};
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" },
];
function ControlledForm() {
const { setFieldValue, setFieldTouched } = useForm({
isControlled: true,
initialValues,
});
return (
<>
<Select
options={options}
onChange={(e) => setFieldValue("candies.iceCream", e)}
onChange={() => setFieldValue("candies.iceCrem")}
/>
<DatePicker
className="form-control mw-100"
showPopperArrow={false}
selected={values.date}
onChange={(e) => setFieldValue("date", e.value)}
onChange={() => setFieldValue("date")}
/>
</>
);
}

Demo

Chocolate
{
  "candies": {
    "iceCream": [
      {
        "value": "chocolate",
        "label": "Chocolate"
      }
    ]
  },
  "date": "2020-05-26T00:00:00.000Z"
}