Skip to main content

Integration an Existing Form

"Easy to use" is one of the core design principles of React Cool Form, the library is built on top of React hook. So it's easy to be integrated with an existing form without too much effort.

Hook into A Form#

To use React Cool Form, we just need to attach the form method to the target element via the ref attribute. It acts as a delegator that will take care of all the values of input, select, and textarea for us.

Edit RCF - Basic

import { useForm } from "react-cool-form";
const Field = ({ label, id, ...rest }) => (  <div>    <label htmlFor={id}>{label}</label>    <input id={id} {...rest} />  </div>);
const Select = ({ label, id, children, ...rest }) => (  <div>    <label htmlFor={id}>{label}</label>    <select id={id} {...rest}>      {children}    </select>  </div>);
const Textarea = ({ label, id, ...rest }) => (  <div>    <label htmlFor={id}>{label}</label>    <textarea id={id} {...rest} />  </div>);
const App = () => {  const { form } = useForm({    // (Strongly advise) Provide the default values    defaultValues: { firstName: "", lastName: "", framework: "", message: "" },    onSubmit: (values) => console.log("onSubmit: ", values),  });
  return (    // We can use "noValidate" to disable browser's interactive validation    <form ref={form} noValidate>      <Field label="First Name" id="first-name" name="firstName" />      <Field label="Last Name" id="last-name" name="lastName" />      <Select label="Framework" id="framework" name="framework">        <option value="">I'm interesting in...</option>        <option value="react">React</option>        <option value="vue">Vue</option>        <option value="angular">Angular</option>        <option value="svelte">Svelte</option>      </Select>      <Textarea label="Message" id="message" name="message" />      <input type="submit" />    </form>  );};

If you need to use the ref of form for other purpose, you can share the ref by the following way:

import { useRef } from "react";import { useForm } from "react-cool-form";
const App = () => {  const formRef = useRef();  const { form } = useForm();
  const setRef = (element) => {    if (element) {      formRef.current = element;      form(element);    }  };
  return <form ref={form}>{/* Some fields... */}</form>;};

Without Using a <form> Element#

React Cool Form is not limited to actual forms. It can be used with any container where inputs are used.

Edit RCF - Without Form Element

import { useForm } from "react-cool-form";
const Field = ({ label, id, error, ...rest }) => (  <div>    <label htmlFor={id}>{label}</label>    <input id={id} {...rest} />    {error && <p>{error}</p>}  </div>);
const App = () => {  const { form, use, submit } = useForm({    defaultValues: { email: "", password: "" },    onSubmit: (values) => console.log("onSubmit: ", values),  });  const errors = use("errors", { errorWithTouched: true });
  return (    <div ref={form}>      <Field        label="Email"        id="email"        name="email"        type="email"        required        error={errors.email}      />      <Field        label="Password"        id="password"        name="password"        type="password"        required        minLength={8}        error={errors.password}      />      {/* We need to manually submit the form */}      <button onClick={submit}>Submit</button>    </div>  );};

Exclude Fields#

You can tell React Cool Form to exclude field(s) via the pre-defined data-rcf-exclude attribute or the excludeFields option, depending on your case.

Edit RCF - Conditional Fields

import { useState } from "react";import { useForm } from "react-cool-form";
const App = () => {  const { from } = useForm({    defaultValues: { username: "", email: "" },    // excludeFields: ["more"], // You can also exclude the field here by passing in name/id/class    onSubmit: (values) => console.log("onSubmit: ", values),  });  const [toggle, setToggle] = useState(false);
  return (    <form ref={form}>      <input name="username" />      <input name="email" type="email" />      <input        name="more" // Used for the "excludeFields" option        type="checkbox"        onChange={() => setToggle(!toggle)}        data-rcf-exclude // Exclude the fields via the pre-defined data attribute      />      {toggle && (        <>          <input name="option" type="radio" value="๐ŸŽ" defaultChecked />          <input name="option" type="radio" value="๐Ÿฅ" />          <input name="option" type="radio" value="๐Ÿ‹" />        </>      )}    </form>  );};