Last active
November 28, 2020 03:39
-
-
Save robrichard/a55a5bea9c1b3d86e27fd888aba73e98 to your computer and use it in GitHub Desktop.
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
class MyForm extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
input: { | |
email: "", | |
name: "" | |
} | |
}; | |
} | |
handleInputChange(newPartialInput) { | |
this.setState(state => ({ | |
...state, | |
input: { | |
...state.input, | |
...newPartialInput | |
} | |
})) | |
} | |
validate() { | |
const errors = {}; | |
const {input} = this.state; | |
if (!input.email) { | |
errors.email = 'Email is required'; | |
} else if (!isEmailValid(input.email)) { | |
errors.email = 'Please enter a valid email'; | |
} | |
if (!input.name) { | |
errors.name = 'Name is required'; | |
} | |
return { | |
errors, | |
isValid: Object.keys(errors).length === 0 | |
}; | |
} | |
render() { | |
const {input} = this.state; | |
const {errors, isValid} = this.validate(); | |
return ( | |
<form onSubmit={() => /* save your form here */}> | |
<div> | |
<input | |
name="email" | |
placeholder="email" | |
value={input.email} | |
onChange={e => this.handleInputChange({email: e.target.value})} | |
/> | |
{!!errors.email && <span>{errors.email}</span>} | |
</div> | |
<div> | |
<input | |
name="name" | |
placeholder="name" | |
value={input.name} | |
onChange={e => this.handleInputChange({name: e.target.value})} | |
/> | |
{!!errors.name && <span>{errors.name}</span>} | |
</div> | |
<div> | |
<button type="submit" disabled={!isValid}> | |
Submit | |
</button> | |
</div> | |
</form> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment