Last active
July 13, 2018 19:48
-
-
Save kjrocker/4beb2f88693ca80fb66f6793550de6bd to your computer and use it in GitHub Desktop.
React Final Form Helpers
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 * as React from 'react'; | |
import { Form, FormProps } from 'react-final-form'; | |
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; | |
const defaultLog = (...args) => console.log('[Final Form Default Submit]', ...args); | |
const finalForm = <Props extends any, Config extends Partial<FormProps>>(config: Config) => ( | |
BaseComponent: React.ComponentType<Props> | |
) => (props: Omit<Props & FormProps, keyof Config | 'component' | 'children' | 'render'>) => ( | |
<Form onSubmit={defaultLog} {...config} {...props} component={BaseComponent} /> | |
); | |
export default finalForm; |
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 * as React from 'react'; | |
import { Field } from 'react-final-form'; | |
import { OnChange } from 'react-final-form-listeners'; | |
const Condition: React.SFC<{ when: string; is: any; children: React.ReactNode }> = ({ when, is, children }) => ( | |
<Field name={when} subscription={{ value: true }}> | |
{({ input: { value } }) => (value === is ? children : null)} | |
</Field> | |
); | |
export interface ErrorProps { | |
name: string; | |
errorRenderer?: React.ComponentType<any>; | |
} | |
const Error: React.SFC<ErrorProps> = ({ name, errorRenderer: Component = 'span', ...rest }) => ( | |
<Field | |
name={name} | |
subscription={{ touched: true, error: true, submitError: true }} | |
render={({ meta: { touched, error, submitError } }) => | |
touched && (error || submitError) ? <Component {...rest}>{error || submitError}</Component> : null | |
} | |
/> | |
); | |
const WhenFieldChanges: React.SFC<{ field: string; becomes: any; set: string; to: any }> = ({ | |
field, | |
becomes, | |
set, | |
to | |
}) => ( | |
<Field name={set} subscription={{}}> | |
{({ input: { onChange } }) => ( | |
<OnChange name={field}> | |
{(value) => { | |
if (value === becomes) { | |
onChange(to); | |
} | |
}} | |
</OnChange> | |
)} | |
</Field> | |
); | |
export { Error, Condition, WhenFieldChanges } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment