Skip to content

Instantly share code, notes, and snippets.

@lookfirst
Created October 9, 2019 09:29
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 lookfirst/558fb2161fd633c7eaab412b851f1c19 to your computer and use it in GitHub Desktop.
Save lookfirst/558fb2161fd633c7eaab412b851f1c19 to your computer and use it in GitHub Desktop.
react-final-form Material-UI TextField
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;
}
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