Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

<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.

like image 854
sheik Avatar asked Dec 28 '18 14:12

sheik


People also ask

How do you pass material UI icons as props?

Pass in the element type of the icon rather than an element (e.g. Done instead of <Done/> ) and then add the className as you render the element (this is the approach in Fraction's answer). Clone the element in order to add the className prop to it.


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

like image 140
Nadun Avatar answered Oct 10 '22 06:10

Nadun


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} />
      ),
     }}
   />
 );
like image 43
Michael Avatar answered Oct 10 '22 05:10

Michael