5.0.1 • Published 4 years ago

clean-forms v5.0.1

Weekly downloads
5
License
MIT
Repository
github
Last release
4 years ago

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.

5.0.1

4 years ago

5.0.0

4 years ago

4.2.0

5 years ago

4.1.3

5 years ago

4.1.2

5 years ago

4.1.1

5 years ago

4.1.0

5 years ago

4.0.0

5 years ago

3.9.1

5 years ago

3.9.0

5 years ago

3.8.2

5 years ago

3.8.1

5 years ago

3.8.0

5 years ago

3.7.1

5 years ago

3.7.0

5 years ago

3.6.0

5 years ago

3.5.0

5 years ago

3.4.0

5 years ago

3.3.0

5 years ago

3.2.0

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.9

5 years ago

3.0.8

5 years ago

3.0.7

5 years ago

3.0.6

5 years ago

3.0.5

5 years ago

3.0.4

5 years ago

3.0.3

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.5.1

5 years ago

2.5.0

5 years ago

2.4.4

5 years ago

2.4.3

5 years ago

2.4.2

5 years ago

2.4.1

5 years ago

2.4.0

5 years ago

2.3.0

5 years ago

2.2.3

5 years ago

2.2.2

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.3

6 years ago

2.1.2

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago

0.1.0

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago

0.0.0

6 years ago