React Js Form Validation and Conditional Select Example
React Js Form Validation and Conditional Select Example
React Js Form Validation and Conditional Select Example
Html:
1 2 3 4 5 6 7 |
<div id="container" class="ui two column centered grid"> <div class="column"> <h1 class="ui dividing header">React Form</h1> <div id="content"></div> </div> </div> |
Css:
1 2 3 |
#container { margin-top: 6em; } |
Js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
const Dropdown = semanticUIReact.Dropdown; const SemanticForm = semanticUIReact.Form; const SemanticButton = semanticUIReact.Button; const COURSES = {core: ["javascripting","git-it","Scope Chains & Closures","Elementary Electron","learnyounode","How to npm","stream-adventure","how-to-markdown"], electives: [ "Functional Javascript", "Level Me Up Scotty!", "ExpressWorks", "Make Me Hapi", "Promise It Won't Hurt", "Async You", "NodeBot Workshop", "Going Native", "Planet Proto", "WebGL Workshop", "ESNext Generation", "Test Anything", "Tower of babel", "learnyoumongo", "regex-adventure", "learn-sass", "Pattern Lab Workshop", "learnyoubash", "Currying in JavaScript", "Shader School", "Bytewiser", "Bug Clinic", "Browserify Adventure", "Intro to WebGL", "Count to 6", "Kick off Koa", "LololoDash", "learnyoucouchdb", "learnuv", "Learn Generators", "learnyoureact", "perfschool", "Web Audio School", "torrential", "Thinking in React", "Post-mortem debugging", "Seneca in practice", "LESS is more" ],}; class Form extends React.Component { state = { people: [{name:'potato', email:'potato@person.com', department:'core', course:'javascripting'}], fields: { name: '', email: '', department: null, course: null, }, fieldErrors: {}, }; onInputChange = ({name, value, error}) => { const fields = this.state.fields; const fieldErrors = this.state.fieldErrors; fields[name] = value; fieldErrors[name] = error; this.setState({ fields, fieldErrors }); }; onFormSubmit = evt => { const people = [ ...this.state.people ]; const person = this.state.fields; evt.preventDefault(); // prevents page from reloading on submit if (this.validate()) return; this.setState({ people: people.concat(person), fields: { name: '', email: '', }, }); }; validate = () => { // Checks data is valid at form level // To pass this check neither field can be empty and they must pass field level validation const person = this.state.fields; const fieldErrors = this.state.fieldErrors; const errMessages = Object.keys(fieldErrors).filter(k => fieldErrors[k]); if (!person.name) return true; if (!person.email) return true; if (!person.course) return true; if (!person.department) return true; if (errMessages.length) return true; return false; }; render() { return ( <div> <h2 className="ui header">Sign Up Sheet</h2> <SemanticForm onSubmit={this.onFormSubmit}> <Field name="name" onChange={this.onInputChange} placeholder="Name" value={this.state.fields.name} validate={val => val ? false : 'Name Required'} /> <Field name="email" onChange={this.onInputChange} placeholder="Email" value={this.state.fields.email} validate={val => validator.isEmail(val) ? false : 'Invalid Email'} /> <CourseSelect onChange={this.onInputChange} department={this.state.fields.department} course={this.state.fields.course} /> <br /> <SemanticButton type="submit" disabled={this.validate()}>Submit Form</SemanticButton> </SemanticForm> <hr /> <h3>People</h3> <div className="ui list"> {this.state.people.map((person,i) => (<li className="item" key={'person-'+i}><i className="user icon"></i>{person.name} - {person.email} - {person.department} - {person.course}</li>) )} </div> </div> ); } } class Field extends React.Component { static propTypes = { placeholder: PropTypes.string, name: PropTypes.string.isRequired, value: PropTypes.string, validate: PropTypes.func, onChange: PropTypes.func.isRequired, }; state = { value: this.props.value, error: false, }; componentWillReceiveProps(update) { // This is needed because the value prop is set to state (not just passed through) // The state won't automatically update from the prop after it has been initially set this.setState({ value: update.value }); }; onChange = evt => { const name = this.props.name; const value = evt.target.value; const error = this.props.validate ? this.props.validate(value) : false; this.setState({value, error}); this.props.onChange({name, value, error}); }; render() { return ( <div className="field"> <label>{this.props.placeholder}</label> <input placeholder={this.props.placeholder} value={this.state.value} onChange={this.onChange} /> {this.state.error && <div className="ui visible warning message">{this.state.error}</div>} </div> ); }; } class CourseSelect extends React.Component { static propTypes = { department: PropTypes.string, course: PropTypes.string, onChange: PropTypes.func.isRequired, }; state = { department: null, course: null, courses: [], _loading: false, }; componentWillReceiveProps(update) { this.setState({ department: update.department, course: update.course, }); } onDepartmentSelect = (evt, data) => { const department = data.value; const course = null; const courses = COURSES[department] || []; this.setState({ department, course, courses }); this.props.onChange({name: 'department', value: department}); this.props.onChange({name: 'course', value: course}); }; onCourseSelect = (evt, data) => { const course = data.value; this.setState({ course }); this.props.onChange({name: 'course', value: course}); } renderDepartmentSelect = () => { const departmentOptions = [ {text: "", value: ""}, {text: "NodeSchool: Core", value: "core"}, {text: "NodeSchool: Electives", value: "electives"}, ] return ( <div className="field"> <label>Department</label> <Dropdown placeholder="Which department?" fluid={true} selection={true} options={departmentOptions} value={this.state.department || ''} onChange={this.onDepartmentSelect} /> </div> ); }; renderCourseSelect = () => { const courseOptions = [{text:'', value: ''},] .concat(this.state.courses.map(courseOption => { return {value: courseOption, text: courseOption,}; })); return ( <div className="field" hidden={!this.state.courses.length}> <label>Course</label> <Dropdown placeholder="Which course?" fluid={true} selection={true} options={courseOptions} value={this.state.course || ''} onChange={this.onCourseSelect} /> </div> ); // return (<div></div>); }; render() { return ( <div> {this.renderDepartmentSelect()} {this.renderCourseSelect()} </div> ); } } ReactDOM.render( <Form />, document.getElementById('content') ); |
Source Code: https://codepen.io/parc6502/pen/Koajzd