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

@curiouser/react-forms

v0.58.1

Published

A simple library for rendering React forms and form fields along with managing form state and validation

Downloads

74

Readme

@curiouser/react-forms

Features

  • boilerplate-free field label and error rendering
  • validation tests and error messages as data and functions with support for validations conditioned upon form data
  • library of common form fields with support for supplying your own field components
  • use default store (component state) or supply your own functions describing how to write field values (you're responsible for supplying a values prop)
  • model first architecture-ready; bundle validations and data transformations into a single prop
  • observable
  • toggle validateAsYouGo
  • support for complex form data structures including collections, nested objects and collections, etc
  • support for collections with boilerplate management of persistent and temporary data

Install

NPM

npm install @curiouser/react-forms

Yarn

yarn add @curiouser/react-forms

Usage

Render a simple form

A simple login form with validation that requires both fields to be filled in and a password of at least 6 characters.

As a functional component (in the future hooks may be available)

import React from 'react';

import { Form, validator } from '@curiouser/react-forms';
import { PasswordField, TextField } from '@curiouser/react-forms';
import '@curiouser/react-forms/dist/index.css';

const formProps = {
  formName: 'my-form',
  initialValues: {
    password: '',
    username: '',
  },
  validations: [{
    names: [ 'username', 'password' ],
    tests: [[ validator.tests.required, validator.messages.required ]],
  }, {
    names: [ 'password' ],
    tests: [[ validator.tests.minLength(6), validator.messages.minLength(6) ]],
  }],
}

export default function MyForm () {
  const form = React.useRef();

  const handleSubmit = React.useCallback(() => {
    if (!form.current.validate() || form.current.state.isLoading) return;

    const formData = form.current.getData();

    // do something with formData...
  }, []);

  return (
    <Form ref={form} {...formProps}>
      <form onSubmit={handleSubmit}>
        <div className="form__fields">
          <TextField label="Name" name="username" />
          <PasswordField label="Password" name="password" />
        </div>
        <button type="submit">Sign in</button>
      </form>
    </Form>
  );
}

As a class component leveraging inheritance

import React from 'react';

import { Form, util, validator } from '@curiouser/react-forms';
import { PasswordField, TextField } from '@curiouser/react-forms';
import '@curiouser/react-forms/dist/index.css';

class MyForm extends Form {
  static defaultProps = {
    ...Form.defaultProps,
    formName: 'my-form',
    initialValues: {
      password: '',
      username: '',
    },
    validations: [{
      names: [ 'username', 'password' ],
      tests: [[ validator.tests.required, validator.messages.required ]],
    }, {
      names: [ 'password' ],
      tests: [
        [ validator.tests.minLength(6), validator.messages.minLength(6) ],
        [ validator.tests.minLength(8), () => `Password is weak, consider making it 8 characters or more`), { warning: true } ],
      ],
    }],
  };

  constructor (...args) {
    super(...args);
    util.bindMethods(this);
  }

  handleSubmit () {
    if (!this.validate() || this.state.isLoading) return;

    const formData = this.getData();

    // do something with formData...
  }

  render () {
    return super.render(
      <form className="form" onSubmit={this.handleSubmit}>
        <div className="form__fields">
          <TextField label="Name" name="username" />
          <PasswordField label="Password" name="password" />
        </div>
        <button type="submit">Sign in</button>
      </form>
    );
  }
}

More examples in the repo

Run all of the form examples in your browser with yarn start. Here are some common examples:

Extending with your own form field components

Form fields are broken into two, one representing the field (with label, error messaging and className generation) and the actual input/control component.

Field component

import React from 'react';
import Field from 'form/dist/components/fields/Field.jsx';
import NativeSelect from './NativeSelect.jsx';

export default function NativeSelectField (props) {
  return <Field {...props} ref={props.forwardedRef} component={NativeSelect} type="select" />
}

Input/Control component

import React from 'react';
import { util } from '@curiouser/react-forms';

export default function NativeSelect ({ forwardedRef, getValue, id, options, placeholder, required = true, setValue }) {
  const handleChange = React.useCallback((e) => setValue(e.target.value), [ setValue ]);

  return (
    <select id={id} onChange={handleChange} ref={forwardedRef} value={getValue()}>
      {util.renderIf(placeholder, () => (
        <option disabled={required} value="">{placeholder}</option>
      ))}
      {options.map(o => (
        <option key={o.value} value={o.value}>{o.label}</option>
      ))}
    </select>
  );
}

Styles

You're responsible for importing or linking the stylesheet with import '@curiouser/react-forms/dist/index.css'; or any other way you like, it's just a css file. The package styles don't try to do anything pretty for you, just provide functional styles. Class names try to follow the BEM naming convention.

CSS variables

The exported stylesheet predefines these CSS variables that you're encouraged to override.

.form {
  --form-color-error: red;
  --form-color-gray: #dedede;
  --form-color-warning: #fc9403;
  --form-field-height: 46px;
}

License

MIT © curiousercreative