Basically the form take a submit handler, then call the handler with form state,
if all validations pass.
importReactfrom'react'
import{Form,Field,isEmail}from'formaction';
classExampleextendsReact.Component{
handleSubmit(values){
console.log(values);
}
render(){
return(
<Form
initialValues={{'Forms with fun':'hola'}}
onSubmit={values=>this.handleSubmit(values)}
>
<Field
name='name'
type='text'
/>
<Field
name='labeledField'
type='email'
label='Email'
validators={[isEmail]}
/>
<buttontype='submit'>Click me</button>
</Form>
);
}
}
Can I controll my form?
Yes, you can pass state and a onChange handler to form, and controll it by yourself.
Knows what it means? Exactually, if we need it, we can store the form state in redux.
It's still running validations before successfully submitting the form.
importReactfrom'react'
import{Form,Field,isEmail}from'formaction';
classExampleextendsReact.Component{
constructor(){
super();
this.state={
form:{}
}
}
handleSubmit(values){
console.log(values);
}
handleChange(form){
this.setState({
form
});
}
render(){
return(
<Form
initialValues={{'name':'Gabriel Oak'}}
onSubmit={values=>this.handleSubmit(values)}
onChange={values=>this.handleChange(values)}
values={this.state.form}
>
<Field
name='name'
type='text'
/>
<Field
name='email'
type='email'
validators={[isEmail]}
/>
<buttontype='submit'>Click me</button>
</Form>
);
}
}
Creating a personalised component
Fild component may have a renderComponent property, it takes a component, that component
will be rendered rather than native html input. Field will pass by props all the native input
props, like value and onChange, and a meta object. Meta contains info about validators errors and
if field has been touched.
importReactfrom'react'
import{Form,Field,isRequired}from'formaction';
constrenderSelect=props=>{
const{input,meta:{touched,errors}}=props;
return(
<div>
<select
{...input}
>
<optionvalue='happiness'>Be happy</option>
<optionvalue='cool'>Be coll</option>
</select>
<div>
{touched&&errors[0]}
</div>
</div>
);
}
classExampleextendsReact.Component{
handleSubmit(values){
console.log(values);
}
render(){
return(
<Form
onSubmit={values=>this.handleSubmit(values)}
>
<Field
name='someCoolLabel'
renderComponent={renderSelect}
validators={[isRequired]}
/>
<Field
name='name'
type='email'
validators={[isEmail]}
/>
<buttontype='submit'>Click me</button>
</Form>
);
}
}
Validators:
Validators are just pure functions, they receive input value, and do something, and then return a
string containing the error, or just undefined. You can build your own validators.