Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of 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'>Title</label>
                <div >            
                  <MyTextField style={{width:'60%'}}  placeholder='Designer' name='Title' type='input' />
                </div>
                  ...
              </div>
            </Form>
          )}
        </Formik>
      </div>
    )
}

However, I am facing an issue where I cannot add a new "Icon" property or InputProp since

<FieldAttributes<{}>>
does not accept it. How can I work around this limitation and define a new property for the FieldAttributes?

Answer №1

Customize the input field using TextField Props InputProps

Enhance the prefix/suffix with startAdornment and endAdornment

Add an icon inside InputAdornment for additional flair

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>
    )
  }}
/>

https://i.stack.imgur.com/rADhD.png


Resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

crafting connections in 3D using TypeORM (ORM)

I attempted to construct a database schema involving users, groups, documents, and permissions. Users can be part of multiple groups Groups can have multiple users Users can possess permissions for documents Groups can have permissions for documents Perm ...

Create an animated underline for two CSS tabs

I'm interested in learning how to create a similar animation using JS, jQuery, or Vue Transitions with Bootstrap. I want to achieve the effect of moving the line under TAB1 to the right when TAB2 is clicked. Can anyone guide me on animating the div sm ...

What is causing the SVG element to malfunction on iOS devices?

I am facing an issue with the <h1> tag in my design. The SVG element within it is not appearing on mobile phones when I write a media query for devices with a minimum width of 400px, even though it works fine on screens with a minimum width of 800px. ...

Adding images to my CSS markup in a SASS file within Next JS

As a beginner in JavaScript frameworks and webpack, I am facing some issues while trying to import an image in my CSS file. This is the structure of my project; https://i.stack.imgur.com/yVYfu.png This is how my next.config.js file looks like; // next. ...

Instructions for utilizing float:left and list-style-type within HTML are as follows: I am currently experiencing issues with implementing the float:left and list-style-type properties in my code

I'm attempting to align a button list to the left using the float: left property and also remove list styles, but for some reason it's not working as expected. //CSS #tus{margin:5px;padding:0;width:640px;height:auto;} #tus ul{margin:0px;padding: ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...

Adjust the height of the div element to match the screen height with AngularJS controller

Can someone please assist me in resolving this issue? I'm currently working on a div element that displays data (positioned on the left side of the screen). I want to add a scrollbar exclusively to this div. I managed to achieve this by using the fol ...

It appears that React Native's absolute paths are not functioning as expected

I have been attempting to set up React Native with absolute paths for easier imports, but I am having trouble getting it to work. Here is my tsconfig.json: { "compilerOptions": { "allowJs": true, "allowSynthetic ...

Just made the switch to Mongoose 5.12 and hit a snag - unable to use findOneAndUpdate with the $push operator

After upgrading to Mongoose 5.12 from 5.11 and incorporating Typescript, I encountered an issue with my schema: const MyFileSchema = new Schema<IMyFile>({ objectID: { type: String, required: true }, attachments: { type: Array, required: false ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

The steps for accessing the NextJS Router in a class component are straightforward

I have been working with the following HOC in my NextJS project. My goal is to utilize the NextJS router using the withRouter HOC for class components like this: import UserManager from "../managers/user_manager"; import LogInPage from "../ ...

When using shallow rendering, an empty object is returned while calling wrapper.debug() will display the fully rendered component

Apologies if this has already been asked, but I'm still struggling to find the answer. I'm currently working on testing a functional component that renders react-bootstrap components. While the smoke test is successful, I'm having difficulty ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

Rendering React Js component occurs just once following a state update

My journey with ReactJS is just beginning, and I'm facing an unusual issue which might be due to my unconventional implementation approach. Previously, everything was working smoothly. However, when I tried to introduce new features, things started g ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...

What steps should be taken to refresh an Expo app block once new data is retrieved from the database

I'm facing an issue with connecting my expo app to a database. I have utilized react redux to fetch data from the database, and upon successful retrieval of data, I aim to update my furniture block with the obtained information. However, despite recei ...

How can I use CSS to transform a "+" symbol to an "x"?

When I created an accordion using HTML, JS, and CSS, I encountered a problem. The "+" sign in the accordion does not rotate correctly as it should. Instead of rotating from the middle of the "+" sign, it rotates from the top. This is my HTML code: <di ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

The issue of anchor links (#) not functioning properly when navigating within the same page of a Next.JS app router

I've encountered an issue with the <Link/> component in my Next.js app. I've set the href to #targetDiv, expecting the page to scroll to the corresponding section with the id #targetDiv upon clicking. However, this functionality is not work ...