npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-hooks-yup-form

v0.1.5

Published

React simple form on hooks, makes use of yup validation

Downloads

288

Readme

React hooks form with yup validation

This form combines bits of Formik api with the author's personal approach on how to make it more easy in use and more dynamic in the same time.

The react hooks system was applied so the least compliant react version is 16.8.

The form is fast and lightweight, easy to use (see /examples).

The form could make use of plain validation functions as well as yup validation schema on both: form and field levels.

Install

npm i react-hooks-yup-form
or
yarn add react-hooks-yup-form

Run examples

yarn start or npm start

Simple form example with field-level validation

import { Dropdown, Submit, Field, Form } from 'react-hooks-yup-form';
import * as yup from 'yup';

const onSubmit = values => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("submitted:", values);
      resolve("done!");
    }, 1000);
  });
};

function SimpleForm() {
  const [submitOn, setSubmitOn] = useState(true);

  return (
      <Form onSubmit={onSubmit}>
        <fieldset>
          <Field
            name="userName"
            label="*User name"
            preserveValuesOnReset={true} // This field doesnt clear on submit
            validate={value => (value ? "should be empty" : null)} // plain on-field validation
          />
          <Field
            name="url"
            label="*Url"
            placeholder="https://some.url.com"
            yupSchema={yup
              .string()
              .url("Must be URL")
              .required("Required")} // yup on-field validation
          />
          <Field
            name="fruit"
            label="*Select a fruit"
            component={Dropdown}
            placeholder="Choose your favorite fruit"
            validate={value => (value ? "should be empty" : null)} // plain on-field validation
            options={[
              { label: "Grapefruit", value: "Grapefruit" },
              { label: "Lime", value: "Lime" }
            ]}
          />
          <Submit disableIfInvalid={!submitOn}> // Disable submit button while the form is invalid
            Submit
          </Submit>
        </fieldset>
      </Form>
  );
}

Dynamic form - maintains, submits and validates only actual list of fields

import { Dropdown, Submit, Field, Form } from 'react-hooks-yup-form';

function DynamicForm() {
  const [fields, setFields] = useState([
    {
      name: "first",
      label: "First field",
      value: "Initial field value",
      validate: value => (value ? "should be empty" : null) // plain on-field validation
    },
    {
      name: "second",
      label: "Second field",
      component: Input // component: Input might be not set directly as it is a default input
    },
    {
      name: "third",
      validate: value => (!value ? "required" : null),
      component: Input, // not required, the Input is a default component used by form
      preserveValuesOnReset: true // This field doesn't clear on submit
    },
    {
      name: "select",
      component: Dropdown,
      placeholder: "Make your choice",
      validate: value => (!value ? "required" : null),
      options: [
        { value: "grapefruit", label: "Grapefruit" },
        { value: "lime", label: "Lime" },
        { value: "coconut", label: "Coconut" },
        { value: "mango", label: "Mango" }
      ]
    },
    { name: "dt", type: "date" }
  ]);

  return (
    <>
      <button
        onClick={function RemoveField() {
          setFields(fields.slice(0, fields.length - 1));
        }}
      >
        Delete a field, then only rest of the fields will be submitted
      </button>

      <Form onSubmit={onSubmit}>
        <fieldset>
          {fields.map(({ children, ...fieldProps }) => (
            <Field {...fieldProps} key={fieldProps.name} />
          ))}
          <Submit>Submit</Submit>
        </fieldset>
      </Form>
    </>
  );
}

Form with nested fields and field-level validation

import * as yup from 'yup';
import { Dropdown, Submit, Field, Form } from 'react-hooks-yup-form';

const ValidationSchema = yup.object().shape({
  userNick: yup.string().required("Required"),
  user: yup.object().shape({
    name: yup.string().required("Required"),
    password: yup.string().required("Required")
  })
});
/*
If you prefer use plain validation rather then yupSchema,
 make sure it returns results in the following format: 
 {fild_name1: error_message, fild_name2: error_message2, ...} or falsy.

Use "validate" prop to provide plain validation not "yupSchema".
If you have set up both the yupSchema will win.
 */

function NestedForm() {
  const [submitOn, setSubmitOn] = useState(true);

  return (
      <Form onSubmit={onSubmit} yupSchema={ValidationSchema}>
        <fieldset>
          <Field name="userNick" />
          <Field name="user.name" label="*Nested field name: user.name" />
          <Field name="user.password" type="password" />
          <Submit>Submit</Submit>
        </fieldset>
      </Form>
  );
}

 

The form will submit user data as a nested object:

userNick: 'something',
user: {
        name: 'some-name',
        password: 'pass'
    }
}