4
votes

I have designed a form with validation using TypeScript Material UI and Formik. I want a material UI Icon to appear in my textfield area, here's my code:


import React from 'react'
import { Formik, Form, FieldAttributes,useField} from 'formik'
import { TextField } from '@material-ui/core'
import CalendarTodayIcon from '@material-ui/icons/CalendarToday'
import * as yup from 'yup'
import './MainInfo.css'

const MyTextField: React.FC<FieldAttributes<{}>> = ({
  placeholder,type,className,style,
  ...props
}) => {
  const [field, meta] = useField<{}>(props);
  const errorText = meta.error && meta.touched ? meta.error : "";
  return (
    <div className='container'>
    <TextField
    placeholder={placeholder}
    className={className}
    style={style}
    type={type}
    {...field}
    helperText={errorText}
    error={!!errorText}
    id="outlined-basic" 
    variant="outlined"
  />
    </div>
  );
};

export function MainInfo() {

    return (
      <div>
        <Formik
          validateOnChange={true} validationSchema={validationSchema} initialValues={{ Title: '', ActivationDate: '', ExpirationDate: '', DirectManager: '', HRBP: '' }} onSubmit={(data) => {
            console.log(data)
          }}
        >
          {({values, errors}) => (
            <Form id='my-form' >
              <div>
                <label className='label'>عنوان</label>
                <div >            
                  <MyTextField style={{width:'60%'}}  placeholder='طراح' name='Title' type='input' />
                </div>
                  ...
              </div>
            </Form>
          )}
        </Formik>
      </div>
    )
}

but the problem is that I can not add a new Icon property or InputProp since <FieldAttributes<{}>> doesnt accept it. how can I define a new property for the FieldAttributes or fix this issue?

1
TextField eventually is an <input> element, which doesn't really have an option to contain an icon. Do you want to explain what exactly you need?Dekel

1 Answers

8
votes

Use the TextField Props InputProps to customize the input field

And use startAdornment, endAdornment to customize the prefix/suffix

Finally use icon inside InputAdornment would be fine

import { TextField, InputAdornment } from "@material-ui/core";
import ExpandLess from "@material-ui/icons/ExpandLess";
import ExpandMore from "@material-ui/icons/ExpandMore";

<TextField
  id="standard-basic"
  label="Standard"
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <ExpandLess />
      </InputAdornment>
    ),
    endAdornment: (
      <InputAdornment position="end">
        <ExpandMore />
      </InputAdornment>
    )
  }}
/>

enter image description here


Refer: