reactjsvalidationmaterial-uireact-forms

How to change Material UI component property according to props


This is my react js code with MUI TextField and I need to apply error and helperText property when error prop has a value. default error prop value is null.

import React from 'react'
import { TextField } from '@mui/material'

const InputField = (props) => {

const { name, label, value,error=null, onChange } = props;

  return (
    <TextField
        variant='outlined'
        label={label}
        name={name}
        value={value}
        onChange={onChange}
        {...{error && {error:true,helperText:error}}}
    />
  )
}

export default InputField 

The error is on this line. How I figer it on MUI 5.10.9 version

{...{error && {error:true,helperText:error}}}

Solution

  • use error and helperText prop directly without condition. also use space character inside helperText to avoid height issue when there is no error present. https://mui.com/material-ui/react-text-field/#helper-text

    <TextField
      variant='outlined'
      label={label}
      name={name}
      value={value}
      onChange={onChange}
      error={!!error}
      helperText={error || ' '}
    />