Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.