Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

React input field with icon example

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, I am going to show you. how to Input Field with icon in react js with code example.

Install MUI:

Emotion library is required to create react components that have styles attached to them.

npm install @mui/material @emotion/react @emotion/styled

Let’s add two new props – startIcon and endIcon; each will accept any element as a value. Then, in InputProp, we can dynamically add and remove InputAdorment based on the icon value:

Let’s look at the following example to understand how it basically works:

App.js

import InputAdornment from "@mui/material/InputAdornment";
import TextField from "@mui/material/TextField";
import AttachMoneyIcon from "@mui/icons-material/AttachMoney";
import QuestionMark from "@mui/icons-material/QuestionMark";
import AccountCircle from "@mui/icons-material/AccountCircle";
import Visibility from "@mui/icons-material/Visibility";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
import Box from "@mui/material/Box";

export default function App() {
  return (
    Box
      className="App"
      sx={{
        display: "grid",
        gridTemplateColumns: "270px 270px",
        gridGap: 10
      }}
    >
      IconTextField
        label="Salary"
        iconStart={AttachMoneyIcon sx={{ color: "green", fontSize: 20 }} />}
        iconEnd={QuestionMark sx={{ color: "#0089ff", fontSize: 20 }} />}
      />
      IconTextField label="Password" iconEnd={Visibility />} />
      IconTextField label="First Name" iconStart={AccountCircle />} />
      IconTextField
        label="Last Name"
        iconEnd={ErrorOutlineIcon sx={{ color: "red" }} />}
      />
    /Box>
  );
}
 
const IconTextField = ({ iconStart, iconEnd, InputProps, ...props }) => {
  return (
    TextField
      {...props}
      InputProps={{
        ...InputProps,
        startAdornment: iconStart ? (
          InputAdornment position="start">{iconStart}/InputAdornment>
        ) : null,
        endAdornment: iconEnd ? (
          InputAdornment position="end">{iconEnd}/InputAdornment>
        ) : null
      }}
    />
  );
};

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Check the output of the above code example.

All the best 👍



This post first appeared on AGuideHUb, please read the originial post: here

Share the post

React input field with icon example

×

Subscribe to Aguidehub

Get updates delivered right to your inbox!

Thank you for your subscription

×