Any way to render Icon based on text field name using material UI?

Viewed 20990
<TextField  
 margin='dense'    
 fullWidth 
 value={this.props.value} 
 name={this.props.name}   
 type={this.props.type} 
 error={this.props.error !== ''}
 helperText={this.props.error !== '' ? this.props.error : ' '}
 onChange={ e => this.handleChange(e) }
 label={this.props.label} 
 variant= {this.props.variant}
 id={this.props.name}   
 InputProps={{
  endAdornment: (
   <AccountCircle />
  ),
 }}
/>

Is there any way to display different Icons based on Text field name? I mean, If the name is Email then display EmailIcon. If profile then displays AccountCircle.

2 Answers

here is a simple solution so you can start it from here

let icon = null; 
if (this.props.name === "Password") {
  icon = <Visibility />;
} else if (this.props.name === "Account") {
  icon = <AccountCircle />;
}
return (
  <div className={classes.root}>
    <TextField
      label={this.props.name}
      className={classNames(classes.margin, classes.textField)}
      InputProps={{
        endAdornment: icon
      }}
    />
  </div>
);

here I have put the name as a prop in this component and depend on that prop I change the icon. you can change this to switch if you wish.

hope you got an idea.

here is a link of a demo: https://codesandbox.io/s/moo68122lp

You can do it in an elegant way, by abstracting like this:

import { AccountCircle, UserIcon, PhoneIcon } from 'some/ui/library';

const icons = {
  account: AccountCircle,
  user: UserIcon,
  phone: PhoneIcon,
};

const FieldIcon = ({ name }) => {
  const Icon = icons[name];
  return Icon ? (<Icon />) : null;
};

const YourComponent = props => (
  <TextField  
     margin='dense'    
     fullWidth 
     value={props.value} 
     name={props.name}   
     type={props.type} 
     error={props.error !== ''}
     helperText={props.error !== '' ? props.error : ' '}
     label={props.label} 
     variant= {props.variant}
     id={props.name}   
     InputProps={{
      endAdornment: (
       <FieldIcon name={props.name} />
      ),
     }}
   />
 );

Related