Home > Enterprise >  How to make a reusable MUI v5 TextField component with conditional adornment
How to make a reusable MUI v5 TextField component with conditional adornment

Time:11-20

I trying to make a flexible and reusable MUI v5 TextField component but it's not clear how to set default endAdornment or startAdornment on InputProps based on condition.

TextField suppoused to have several states:

  • Default - just regular input
  • Error - if TextField has error prop then endAdornment should be added with a specific icon
  • Search - startAdornment should be added with a specific icon

At the moment I only have (and actually I want to make it work this way):

<StyledTextField
  error={true}
/>

<StyledTextField
  someSearchProp = {true}
/>

Also I want to save an onption to use TextField in a default way like this:

<StyledTextField
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <SearchIcon />
      </InputAdornment>
    ),
  }}
/>

StyledTextField.tsx

const StyledTextField: React.FC<StyledTextFieldProps> = ({ ...props }) => (
  <TextField
    {...props}
    InputProps={{
      endAdornment: (
        <InputAdornment position="end">
          <InfoOutlinedIcon color={'error'} />
        </InputAdornment>
      ),
    }}
  />
);

aaa

CodePudding user response:

You can spread props and add new value to InputProps key

sth like this :

    const StyledTextField: React.FC<StyledTextFieldProps> = (props) => {
    
      let textFieldProps = props
    
    if(props.error){
      textFieldProps = {...props,InputProps:{
          startAdornment: (
            <InputAdornment position="start">
              <SearchIcon />
            </InputAdornment>
          ),
        }}
      delete textFieldProps.error
    }else if(props.someSearchProp){
      textFieldProps = {...props,InputProps:{
          endAdornment: (
            <InputAdornment position="end">
              <InfoOutlinedIcon color={'error'} />
            </InputAdornment>
          )
        }}
      delete textFieldProps.someSearchProp
    }
    
   return ( <TextField
      {...textFieldProps}
    />)
   };

after assigning value I remove error and someSearchProp properties because they are not TextField props and cause warning in console

  • Related