Created
August 29, 2017 07:20
-
-
Save JasperVercammen/bdcd23ad32fe0caab50c9772574901ba to your computer and use it in GitHub Desktop.
Component based form handling React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import './home.css'; | |
const FIELDS = [ | |
{name: 'name', type: 'text', validationRule: 'text', isRequired: true}, | |
{name: 'lastname', type: 'text', validationRule: 'text', isRequired: true}, | |
{name: 'dob', type: 'date', validationRule: 'date'}, | |
{name: 'email', type: 'text', validationRule: 'email'}, | |
{name: 'gender', type: 'radio', validationRule: 'gender', values: ['F', 'M']}, | |
]; | |
class Home extends Component { | |
constructor(props) { | |
super(props); | |
this.state = {errors: []}; | |
} | |
onFieldChange = (event) => { | |
const target = event.target; | |
const {name, value} = target; | |
this.setState( | |
{ | |
[name]: value, | |
}); | |
}; | |
onSubmit = (event) => { | |
event.preventDefault(); | |
const errors = FIELDS.map((field) => { | |
const value = this.state[field.name]; | |
if (field.isRequired && !value) { | |
return field.name; | |
} | |
const error = !this.validate(field.validationRule, value); | |
if (error) { | |
return field.name; | |
} | |
return null; | |
}).filter((error) => !!error); | |
if (errors.length) { | |
this.setState({errors}); | |
} else { | |
this.setState({errors: []}); | |
// SUBMIT ALL THE THINGS | |
console.log('SUBMIT'); | |
} | |
}; | |
validate = (type, value) => { | |
switch (type) { | |
case 'email': | |
const condition = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
return condition.test(value); | |
case 'date': | |
// Make a valid date validation | |
break; | |
default: | |
return true; | |
} | |
}; | |
render() { | |
return ( | |
<div className='app'> | |
<form onSubmit={this.onSubmit}> | |
{FIELDS.map((field) => { | |
switch (field.type) { | |
case 'radio': | |
return field.values.map((value) => ( | |
<span key={value}> | |
<input type={field.type} name={field.gender} value={value} onChange={this.onFieldChange} /> {value} | |
</span> | |
)); | |
case 'text': | |
case 'email': | |
default: | |
return <input key={field.name} type={field.type} name={field.name} placeholder={field.name} onChange={this.onFieldChange} />; | |
} | |
})} | |
{this.state.errors.length && <p>This is what you did wrong:</p>} | |
{this.state.errors.map((error) => <p key={error}>{error}</p>)} | |
<input type='submit' value='Submit all the things' /> | |
</form> | |
</div> | |
); | |
} | |
} | |
export default Home; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment