Created
October 9, 2019 09:29
-
-
Save lookfirst/558fb2161fd633c7eaab412b851f1c19 to your computer and use it in GitHub Desktop.
react-final-form Material-UI TextField
This file contains 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, {useContext, createContext} from "react"; | |
import {Schema} from "yup"; | |
export const SchemaContext = createContext<Schema<any> | undefined>(undefined); | |
interface SchemaProviderProps<T> { | |
value: Schema<T>, | |
children: React.ReactNode | React.ReactNode[], | |
} | |
export function SchemaProvider({value, children}: SchemaProviderProps<any>) { | |
return ( | |
<SchemaContext.Provider value={value}> | |
{children} | |
</SchemaContext.Provider> | |
); | |
} | |
export function useSchemaContext() { | |
const context = useContext(SchemaContext); | |
if (!context) { | |
throw new Error('useSchemaContext must be used within a SchemaProvider'); | |
} | |
return context; | |
} |
This file contains 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 from 'react'; | |
import {FieldRenderProps} from 'react-final-form'; | |
import TextField, {TextFieldProps} from '@material-ui/core/TextField'; | |
import {useSchemaContext} from "./SchemaProvider"; | |
export function TextFieldWrapper(props: FieldRenderProps<TextFieldProps, HTMLInputElement>) { | |
const {input: {name, onChange, value, ...restInput}, meta, ...rest} = props; | |
const showError = ((meta.submitError && !meta.dirtySinceLastSubmit) || meta.error) && meta.touched; | |
const schema: any = useSchemaContext(); | |
const required = schema.fields[name]._exclusive.required; | |
return ( | |
<TextField | |
fullWidth={true} | |
helperText={showError ? meta.error || meta.submitError : undefined} | |
error={showError} | |
onChange={onChange} | |
name={name} | |
key={name} | |
required={required} | |
value={value} | |
margin='normal' | |
{...rest} | |
InputLabelProps={{shrink: !!value}} | |
inputProps={restInput as any} | |
/> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment