Created
March 8, 2020 18:59
-
-
Save alexmccabe/ca6bfe0f3742a47e7a7b4127569a899e to your computer and use it in GitHub Desktop.
This file contains hidden or 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, { useCallback, useState } from 'react'; | |
const FormContext = React.createContext({ | |
getInputValue: (name, defaultValue = '') => null, | |
onInputChange: name => e => {} | |
}); | |
function validate(data, rules) { | |
// validate here | |
} | |
function Form(props) { | |
const formState = useState({ data: {} }); | |
const onSubmit = useCallback( | |
event => { | |
event.preventDefault(); | |
validate(formState, props.rules) && props.onSubmit(formState); | |
}, | |
[formState, props.rules] | |
); | |
function getInputValue(name, defaultValue = '') { | |
return this.state.data[name] || defaultValue; | |
} | |
function onInputChange(name) { | |
return function(e) { | |
const targetValue = e.target.value; | |
this.setState(prevState => ({ | |
data: { | |
...prevState.data, | |
[name]: targetValue | |
} | |
})); | |
}; | |
} | |
return ( | |
<FormContext.Provider value={{ getInputValue, onInputChange }}> | |
<form action="" onSubmit={onSubmit}> | |
{props.children} | |
</form> | |
</FormContext.Provider> | |
); | |
} | |
export default Form; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment