Skip to content

Instantly share code, notes, and snippets.

@alexmccabe
Created March 8, 2020 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexmccabe/ca6bfe0f3742a47e7a7b4127569a899e to your computer and use it in GitHub Desktop.
Save alexmccabe/ca6bfe0f3742a47e7a7b4127569a899e to your computer and use it in GitHub Desktop.
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