0.6.0 • Published 4 years ago

react-contextual-forms v0.6.0

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

React Contextual Forms

version

Simple forms for React using context.

Features

  • Easy to use
  • Bring your own components
  • Write your own validators
  • Made with TypeScript (available types)

Installation

This package uses hooks so it requires at least version 16.8 of React.

npm install react-contextual-forms

Usage

After installing the package from NPM you can start using the 3 available components (Form, Field and Interaction) to build your forms.

Components

Form

The 'Form' component is the one that will provide the context for the others, you can place 'Field' and 'Interaction' components within it. There is no restriction on the number of forms you can use next to each other, how many you use or where you place the fields/interactions in the form.

PropTypeRequiredDescription
onChangefunctionnoEvent that triggers when the form changes
onSubmitfunctionyesSubmit event for the form

Field

A 'Field' component only serves as a wrapper for the actual component and provides it with a number of props, how you want to display the field is completely up to you.

PropTypeRequiredDescription
componentFunctionComponent< IFieldComponentProps >yesThe component to render as the field
defaultValuestringnoThe default value of the field
idstringyesID of this field
onChangefunctionnoReturns the value of the field when it changes
propsobjectnoProps of the field which are passed down to the component
validatorsArray< IFieldValidator >noCollection of all validator functions
IFieldComponentProps
NameTypeDescription
errorstring / nullThe error message for the field if there is a validation error, else null
isTouchedbooleanHas the field been touched by the user or not
propsobjectPassed down props from the field
valuestringThe current value of the field
updatefunction(value: string) => void Function to update the field value
IFieldValidator
NameTypeDescription
checkfunction(value: string) => boolean Function to validate the field, must return boolean
messagestringThe error message to show if the validation fails

Interaction

If you find the need to update a form value directly, you can use an 'Interaction' component. Note that these only work when they are located within a Form component.

PropTypeRequiredDescription
componentFunctionComponent< IInteractionComponentProps >yesThe component to render as the interaction
propsobjectnoProps of the interaction which are passed down to the component
IInteractionComponentProps
NameTypeDescription
propsobjectPassed down props from the intercaction
updatefunction(id: string, value: string) => void Function to update field's value

Examples

Javascript

import React from 'react'
import { Form, Field, Interaction } from 'react-contextual-forms'

const formValidators = {
    required: {
        check: (value) => {  
            if (!value) return false
            return true
        },
        message: 'This field is required'
    }
}

const Input = ({ error, isTouched, value, update }) => {
    return (
        <span>
            <input type="text" value={value} onChange={(e) => update(e.target.value)} />
            <p>{(error && isTouched) && error}</p>
        </span>
    )
}

const Select = ({ error, isTouched, value, update }) => {
    return (
        <span>
            <select value={value} onChange={(e) => update(e.target.value)}>
                <option>A</option>
                <option>B</option>
                <option>C</option>
            </select>
            <p>{(error && isTouched) && error}</p>
        </span>
    )
}

const ChangeButton = ({ update }) => {
    return (
        <button 
            type="button" 
            onClick={() => { 
                update('lastname', 'Doe')
                update('firstname', 'John')
            }}
        >Change</button>
    )
}

function App() {
    return (
        <div className="App">
            <p>FORM</p>
            <Form onSubmit={(form) => console.log(form)}>
                <div>
                    <Field id="lastname" validators={[formValidators.required]} component={Input} />
                    <Field id="firstname" validators={[formValidators.required]} component={Input} />
                </div>
                <div>
                    <Field id="choice" defaultValue="B" component={Select} />
                </div>
                <Interaction component={ChangeButton} />
                <button type="submit">Submit</button>
            </Form>
        </div>
    )
}

Typescript

import React from 'react'
import { Form, Field, Interaction, IFieldComponentProps } from 'react-contextual-forms'

const formValidators = {
    required: {
        check: (value) => {  
            if (!value) return false
            return true
        },
        message: 'This field is required'
    }
}

const Input: React.FunctionComponent<IFieldComponentProps> = ({ error, isTouched, props, value, update }) => {
    return (
        <span>
            <label>{props?.label}</label>
            <input type="text" value={value} onChange={(e) => update(e.target.value)} />
            <p>{(error && isTouched) && error}</p>
        </span>
    )
}

function App() {
    return (
        <div className="App">
            <p>FORM</p>
            <Form onChange={(form) => console.log('CHANGE', form)} onSubmit={(form) => console.log('SUBMIT', form)}>
                <div>
                    <Field id="lastname" validators={[formValidators.required]} component={Input} props={{ label: 'Last name' }} />
                    <Field id="firstname" validators={[formValidators.required]} component={Input} />
                </div>
                <button type="submit">Submit</button>
            </Form>
        </div>
    )
}

License

MIT

0.6.0

4 years ago

0.5.2

4 years ago

0.5.1

4 years ago

0.5.0

4 years ago

0.4.3

4 years ago