Skip to content

Instantly share code, notes, and snippets.

@alexmccabe
Created March 8, 2020 14:37
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/7593e84a00dc325211f7b18c08dc1cee to your computer and use it in GitHub Desktop.
Save alexmccabe/7593e84a00dc325211f7b18c08dc1cee to your computer and use it in GitHub Desktop.
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