Created
March 8, 2020 14:37
-
-
Save alexmccabe/7593e84a00dc325211f7b18c08dc1cee 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, useContext, useState } from 'react'; | |
import { connect } from 'react-redux'; | |
import { updateSomeAPIValue } from 'state/APIValue'; | |
const FormContext = React.createContext({ | |
getInputValue: (name, defaultValue = '') => null, | |
inputChange: name => e => {} | |
}); | |
function Input(props) { | |
const context = useContext(FormContext); | |
return ( | |
<input | |
{...props} | |
onChange={context.inputChange(props.name)} | |
value={context.getInputValue(props.name)} | |
/> | |
); | |
} | |
Input.defaultProps = { | |
type: 'text' | |
}; | |
/* Form Component | |
========================================================================== */ | |
function validate(data, rules) { | |
// validate here | |
} | |
function Form(props) { | |
const formState = useState({ input1: '', input2: '' }); | |
const onSubmit = useCallback( | |
event => { | |
event.preventDefault(); | |
validate(formState, props.rules) && props.onSubmit(formState); | |
}, | |
[formState, props.rules] | |
); | |
return ( | |
<FormContext.Provider value={null}> | |
<form action="" onSubmit={onSubmit}> | |
{props.children} | |
</form> | |
</FormContext.Provider> | |
); | |
} | |
/* Custom Component | |
========================================================================== */ | |
export function MyForm(props) { | |
const onFormSubmit = fields => { | |
// Dispatch action provided by mapDispatchToProps | |
props.updateSomeAPIValue(fields); | |
}; | |
return <Form onSubmit={}></Form>; | |
} | |
const mapDispatchToProps = () => { | |
return { | |
updateSomeAPIValue | |
}; | |
}; | |
const mapStateToProps = state => { | |
return {}; | |
}; | |
export default connect(mapStateToProps, mapDispatchToProps)(MyForm); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment