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

clean-forms

v5.0.1

Published

Components to create clean forms with react

Downloads

11

Readme

React Clean Forms

Build Status Coverage Status semantic-release npm version

Forms can be complex and React does not provide a build-in solution to solve this problem. This library provides components to write readable forms that focus on maintainability.

Features

  • Input Validation
  • Dirty/Touched state tracking
  • Full Typescript support
  • Controlled data flow

Getting Started

In Clean Forms every form is composed of Fields. A Field wraps an component to connect it to the api. Let's create a simple Field for an text input. We define how the given value is rendered and updated and how errors are displayed.

// InputField.tsx
import React from 'react';
import { createField } from 'clean-forms';

interface InputFieldProps {
  label: string;
}

export const InputField = createField<
  string,
  InputFieldProps & JSX.IntrinsicElements['input']
>(
  ({
    input: { value, name, onChange, onBlur },
    custom: { label, ...other },
  }) => {
    return (
      <div>
        <input
          value={value}
          name={name}
          onChange={event => onChange(event.target.value)}
          onBlur={onBlur}
          placeholder={label}
          {...other}
        />
      </div>
    );
  }
);

Next, let's build our actual form! We use the "name" property on our fields to define which value is mapped to the field.

// LoginForm.tsx
import React, { useState } from 'react';
import { Form } from 'clean-forms';
import { InputField } from './InputField';

const initialValue = {
  username: '',
  password: '',
};

export function LoginForm() {
  const [value, setValue] = useState(initialValue);

  const handleSubmit = () => {
    alert(JSON.stringify(value, null, 2));
  };

  return (
    <Form value={value} onChange={setValue} onSubmit={handleSubmit}>
      <InputField label="Username" name="username" />
      <InputField label="Password" name="password" type="password" />
      <div>
        <button type="submit">Submit</button>
      </div>
    </Form>
  );
}

That's it! We created a simple login form.

Validation

Currently the user can submit even if he leaves some of the fields empty.

First let's create a function, that checks if the value is set. If this is the case it should return null and an error message otherwise.

// validators.ts
export function required(value: any) {
  if (value == null || value === '') {
    return 'Required';
  }
  return null;
}

We also need to update our field, so it displays validation errors. We don't want to show these errors at the beginning, as this would be overwhelming for the user. Instead we only want to show the error if the user has focused the field. We can use the touched flag for this.

// InputField.tsx
import React from 'react';
import { createField } from 'clean-forms';

interface InputFieldProps {
  label: string;
}

export const InputField = createField<
  string,
  InputFieldProps & JSX.IntrinsicElements['input']
>(
  ({
    input: { value, name, onChange, onBlur, error, touched },
    custom: { label, ...other },
  }) => {
    return (
      <div>
        <input
          value={value}
          name={name}
          onChange={event => onChange(event.target.value)}
          onBlur={onBlur}
          placeholder={label}
          {...other}
        />
        {touched && <div>{error}</div>}
      </div>
    );
  }
);

Now we can use our validator in our form.

// LoginForm.tsx
import React, { useState, useCallback } from 'react';
import { Form, ValidationDefinition } from 'clean-forms';
import { InputField } from './InputField';
import { required } from './validators';


const initialValue = {
  username: '',
  password: '',
};

// We define the validation here
const validation: ValidationDefinition<typeof initialValue> = {
  username: required,
  password: required,
};

export function LoginForm() {
  const [value, setValue] = useState(value);

  const handleSubmit = () => {
    alert(JSON.stringify(value, null, 2));
  };

  return (
    <Form
      state={value}
      onChange={setValue}
      // and just pass it to our form
      validation={validation}
      // We only want to trigger the submit on a valid form
      onValidSubmit={handleSubmit}
    >
      <InputField label="Username" name="username" />
      <InputField label="Password" name="password" type="password" />
      <div>
        <button type="submit">Submit</button>
      </div>
    </Form>
  );
}

The validation definition has the same shape as our data. If you use typescript you get a type error if your definition does not match. We also change the callback from onSubmit to onValidSubmit, so it only gets triggered if our form is valid.

You can checkout the example on Code Sandbox.