Giter Club home page Giter Club logo

react-smart-form's Introduction

react-smart-form

A form component that containes all the functionality you will need.


Installation

Examples

Documentation


Installation

Install with yarn or npm

yarn add react-smart-form
        #or
npm install react-smart-form --save

Examples

Basic

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {Form, Input, Submit} from 'react-smart-form';

class MyComponent extends Component {
    onSubmit=(values)=>{
           console.log(`Username: ${values.username}`);
           console.log(`Password: ${values.password}`);
    }
    render() {
        return (
            <Form onSubmit={this.onSubmit}>
                <Input name="username" label="Username" />
                <Input name="password" label="Password" type="password" />
                <Submit>
                    Login
                </Submit>
            </Form>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

Validation

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {Form, Input, Submit} from 'react-smart-form';
import {required, length, email} from 'react-smart-form/validators';


/* 
* the react-smart-form asks if the field has error 
* so you must return false if it doesn't 
* or true (or a string message) if it does
*/
const numberCustomValidator = message=>(value)=>{
    if(typeof value !== 'number'){
        return message || true;
    }
    return false;
}

class MyComponent extends Component {
    onSubmit=(values)=>{
           console.log(`Username: ${values.username}`);
           console.log(`Password: ${values.password}`);
    }
    render() {
        return (
            <Form onSubmit={this.onSubmit}>
                <Input 
                    name="username" 
                    label="Username" 
                    validators={[required('Email is required'),email('This is not correct email.')]}
                />
                <Input 
                    name="password" 
                    label="Password" 
                    type="password" 
                    // silent validation
                    validators={[required(),numberCustomValidator('This must be a number')]}

                    />
                <Submit>
                    Login
                </Submit>
            </Form>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

Handle custom errors and loading state

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {Form, Input, Submit} from 'react-smart-form';

const fakeRequest = ()=>{
  return new Promise((resolve)=>{
      setTimeout(resolve,1000);
  })  
};

class MyComponent extends Component {
    onSubmit=(values)=>{
           console.log(`Username: ${values.username}`);
           console.log(`Password: ${values.password}`);
           // Returning a promise react-smart-form can handle loading state of the form.
           return fakeRequest().then((resp)=>{
               if(!resp.data.success){
                   throw {
                       username:'This username doesn\'t exist.'
                   }    
               }
               
           });
    }
    render() {
        return (
            <Form onSubmit={this.onSubmit}>
                <Input name="username" label="Username" />
                <Input name="password" label="Password" type="password" />
                <Submit>
                    Login
                </Submit>
            </Form>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

Custom input custom errors and loading state

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {smartForm, smartInput, withFormState} from 'react-smart-form';


let CustomForm = (props)=>{
    const {
        smartForm, // include loading(bool):the loading state of the form, disabled(bool):the disabled state of the form
        children,
        ...formPros
    } = props;
    return (
        <div>
            <form {...formPros}>
            {children}
            </form>
        </div>
  )};

CustomForm=smartForm()(CustomForm); 

let CustomField = (props)=>{
    const {
        smartForm, // include error(string || bool): the error of the field
        label,
        ...inputProps
    }=props;
    return (
        <div>
             <label>Custom field: {label}</label>
             <input {...inputProps} />
             <div>{smartForm.error}</div>
        </div>
  )};

CustomField=smartInput()(CustomField);


let CustomButton = (props)=>{
    const {
        smartForm, // include loading(bool):the loading state of the form, disabled(bool):the disabled state of the form
        ...buttonProps
    } = props;
    return (
        <div>
            <button {...buttonProps} disabled={smartForm.disabled}>
            {smartForm.loading ? 'loading...':children}
            </button>
        </div>
  )};

CustomButton=withFormState(CustomButton);

class MyComponent extends Component {
    render() {
        return (
            <CustomForm onSubmit={this.onSubmit}>
                <CustomField name="email" label="Email" validators={[required('This is required')]}/>
                <CustomButton>Press</CustomButton>
            </CustomForm>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

withValidator only

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {withValidator} from 'react-smart-form';
import {required} from 'react-smart-form/validators';

let CustomField = (props)=>{
    const {
        error
        label,
        ...inputProps
    }
    return (
        <div>
             <label>Custom field: {label}</label>
             <input {...inputProps} />
             <div>{error}</div>
        </div>
  )};

CustomField=withValidator(CustomField);

class MyComponent extends Component {
    render() {
        return (
            <form>
                 <CustomField name="email" label="Email" validators={[required('This is required')]}/>
            </form>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

Reset form

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {Form, Input, Submit} from 'react-smart-form';

class MyComponent extends Component {
    render() {
        return (
            <div>
                <Form formRef={(form)=>{ this.form=form; }}>
                    <Input name="username"/>
                </Form>
                <button onClick={()=>{this.form.reset('username')}}>Reset Username</button>
                <button onClick={()=>{this.form.reset()}}>Reset All</button>
            </div>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

Match password

import React,{ Component } from 'react';
import { render } from 'react-dom';
import {Form, Input, Submit} from 'react-smart-form';
import {required} from 'react-smart-form/validators';


class MyComponent extends Component {
    onSubmit=(values)=>{
           console.log(`Username: ${values.username}`);
           console.log(`Password: ${values.password}`);
    }
    matchPasswordValidator = message=>(value)=>{
        if(value !== this.form.getValues('password')){
            return message || true;
        }
        return false;
    }
    render() {
        return (
            <Form 
            formRef={(form)=>{this.form=form}}
            onSubmit={this.onSubmit}
            >
                <Input 
                    showPassword={false}
                    name="password" 
                    label="Password" 
                    type="password" 
                    // silent validation
                    validators={[required()]}
                    />
                <Input 
                    showPassword={false}
                    name="repassword" 
                    label="Re enter password" 
                    type="password" 
                    validators={[required(),this.matchPasswordValidator('Password does not match')]}
                    />
                    
                <Submit>
                    Register
                </Submit>
            </Form>
        );
    }
}

render(
    <MyComponent/>,
    document.getElementById('app'),
);

Documentation

Form
propType required default description
onValidate(func(hasError)) no - A function that runs every time the overall validation status change
onSubmit(func(FieldValues)) no - the function that handles the form submission
onChange(func(FieldValues)) no - A function that runs every time a field changes
disabled(bool) no - set the form in a disabled state
loading(bool) no - set the form in a loading state
formRef(func) no - returns the Form instance. With form instance you can user reset, setErrors and setValue functions
Input
propType required default description
type(input type or 'textarea') no - The type of the Input. Takes all the valid Input type except file and submit.
name(string)) yes - The name of the input
label(string) no - The value of the label
focusedLabel(string) no - the value of the label when it is focused
icon(react Component) no - sets and icon in the right side of the input
validators([func(value)]) no - An array of functions that validates the inputs value. Should return false if the validation pass and string or true if it dont
onChange(func(value)) no - A function that runs every time the field changes
focused(bool) no - initialize the input in focus state
showPassword(bool) true - if the type of the field is password appends a icon button that toggles the input display state
defaultValue(string) no - sets a default value for the field
inputRef(func) no - returns the input reference
debounce(number) no 300 set the input's debounce for validation
disabled:readOnly (bool) no - set the input in a readOnly state
Submit
propType required default description
size(number) no 18 -
color(string) no '#44A8FF' set the button color
loading(bool) no - set the button in a loading state
disabled(bool) no - set the form in a disabled state
children(string) no - The button label
Validators
name description
email(errorMessage) checks if the input value is valid email
length(errorMessage,{min:number,max:number}) validates the value length
required(errorMessage) checks if a has been set
Form instance function
name description
reset('fieldName') reset the specified field. If no field name, all fields will be reset.
getValues({inputName:value}) Returns the requested value. If no input name an object with all values will be returned
setValues({inputName:value}) Sets values to the specified fields
setErrors({inputName:errorMessage}) Sets errors to the specified fields

react-smart-form's People

Contributors

ssbeefeater avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

shravah nwhitmont

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.