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

context-form-ts

v1.0.0

Published

A helpful library to easily and effectively manage forms with react context

Downloads

2

Readme

context-form-ts

Made with create-react-library

NPM JavaScript Style Guide

Install

npm install context-form-ts

or...

yarn add context-form-ts

Usage

import { withForm, useForm, Field, email, min } from 'context-form-ts';

const Form = withForm(() => {
  const form = useForm();

  const onSubmit = (values) => {
    console.log(values);
    alert(values);
  };

  return (
    <>
      <Field
        name="email"
        placeholder="E-mail"
        type="email"
        className="input"
        validate={email('Must be an email')}
      >
        {({ input, info, ...props }) => (
          <div className="inputContainer">
            <input {...input} {...props} />
            {!!info.error && info.hasBeenTouched && (
              <div className="error">{info.error}</div>
            )}
          </div>
        )}
      </Field>
      <Field
        name="password"
        placeholder="Password"
        type="password"
        className="input"
        validate={min(7, 'Must have 7 characters minimum')}
      >
        >
        {({ input, info, ...props }) => (
          <div className="inputContainer">
            <input {...input} {...props} />
            {!!info.error && info.hasBeenTouched && (
              <div className="error">{info.error}</div>
            )}
          </div>
        )}
      </Field>
      <button onClick={form.handleSubmit(console.log)}>Submit</button>
    </>
  );
});

API

withForm (hoc)

Embeds your component inside the neccesary context to work.

Usage

const Form = withForm(() => {
  ...
  return (
    <>
      {...}
    </>
  );
});

useForm (hook)

A hook that returns the form context value.

const form = useForm();

Context Value

values

Immutable object with the form values.

console.log(form.values);

setValues

Function that receive an object with new form values which will overwrite the past values.

form.setValues({ ...newValues });

setValue

function that sets the value of a key of the form values ​​object.

form.setValue('email', '[email protected]');

errors

Immutable object with the form value errors.

console.log(form.errors);

setErrors

Function that receive an object with new form value errors which will overwrite the past errors.

form.setErrors({ ...newErrors });

setError

function that sets the value of a key of the form errors ​​object.

form.setError('email', 'Must be a registered e-mail.');

defaultValues

Immutable object with the form defaultValues.

console.log(form.defaultValues);

setDefaultValues

Function that receive an object with new form default values which will overwrite the past default values.

form.setDefaultValues({ ...newDefaultValues });

setDefaultValue

function that sets the value of a key of the form default values ​​object.

form.setDefaultValue('email', '[email protected]');

cleanForm

function that sets the form values as a new empty object.

form.cleanForm();

resetForm

function that returns the form values object to its initial value (with the default values)

form.cleanForm();

handleSubmit

Function that receives a submit function as param and returns the received function bound with new functionality for the form, such as the corresponding verification of the form values before calling the submit function.

const onSubmit = (values) => {
  console.log(values);
  alert(values);
};

return (
  <>
    {...}
    <button onClick={form.handleSubmit(onSubmit)}>
      Submit
    </button>
    {...}
  </>
);

Field (React Component)

A component that receives as children a function which will be have as params all the necessary data for the field.

Props

| prop | type | description | | :----------: | :-------------------: | :-------------------------------------------------------------------------- | | name | string | the input name which will be the key of the input in the form values object | | defaultValue | string | undefined | default value of the input | | children | function | Info below.... | | validate | function | undefined | Info below... |

children

A function that will render the input with some data that it will receive as param

Param that will be sent to the children function

param {
  name: string,
  input: {
    onChange: input onBlur event handler function,
    onBlur: input onBlur event handler function,
    value: any,
  },
  info: {
    hasBeenTouched: boolean,
    hasChanged: boolean,
    error: string | true | undefiend,
  },
  {...allTheOtherPropsThatYouPassedToTheFieldComponent}
}

Example

<Field name="email" validate={email('Must be an email')}>
  ({name, input, info, ...props}) => {
    <input
      name={name} // unnecesary
      {...props}
      {...info}/>
    {!!info.error && info.hasBeenTouched && (
      <p>{info.error}</p>
    )}
  }
</Field>

validate

Function that receives the input value as param and returns true or string if there is any error.

  const validate = (value) => {
    if (!(value === 'correct value')) return 'Incorrect value';
  };

  return (
    {...}
      <Field {...props} validate={validate} />
    {...}
  );

This library has various validate function generators that you can use. See below.

Validate function generators by the library

import {
  required,
  min,
  max,
  email,
  alphanumeric,
  alpha,
  numeric,
  lowercase,
  uppercase,
} from 'context-form-ts';

required

<Field
  name="name"
  type="text"
  validate={required()}>
  {...}
</Field>

min

<Field
  name="age"
  type="number"
  validate={min(0, 'You must born first')}>
  {...}
</Field>
<Field
  name="name"
  type="text"
  validate={min(4, 'Must have 4 characters minimum')}>
  {...}
</Field>

max

<Field
  name="age"
  type="number"
  validate={max(150, 'You must be alive')}>
  {...}
</Field>
<Field
  name="name"
  type="text"
  validate={max(19, 'Must have 19 characters maximum')}>
  {...}
</Field>

email

<Field
  name="email"
  type="email"
  validate={email('Must be an e-mail')}>
  {...}
</Field>

alphanumeric

<Field
  name="username"
  validate={alphanumeric('Must be alphanumeric')}>
  {...}
</Field>

alpha

<Field
  name="username"
  validate={alpha('Must have only letters')}>
  {...}
</Field>

numeric

<Field
  name="code"
  validate={numeric('Must have only numbers')}>
  {...}
</Field>

lowercase

<Field
  name="username"
  validate={lowercase('Must be lowecase')}>
  {...}
</Field>

uppercase

<Field
  name="username"
  validate={uppercase('Must be lowecase')}>
  {...}
</Field>

License

MIT © fabiosaac12