Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reactjs TextField helperText

how can I synchronize error validation with the character limit without affecting its functions, please see this https://codesandbox.io/s/nostalgic-mestorf-47jsvk?file=/src/App.js

  const [formError, setFormError] = useState(false);
  const CHARACTER_LIMIT = 1000;
  const [getString, setString]= useState({
    value: "",
    length: 0
  })


const onHandleChangeInput = (field, value) => {
  setString({value: value, length: value.length})
}
  const onHandleInputValidation = (field, value) => {
    try {
      Joi.assert(value, _.get(VALIDATION_SCHEMA, field));
      setFormError(_.omit(formError, field));
      return { error: false, valid: true };
    } catch (err) {
      return { error: err.message, valid: false };
    }
  };
    <TextField
      label="Name"
      inputProps={{
        maxlength: CHARACTER_LIMIT
      }}
      values={getString.name}
      onChange={(value) => onHandleChangeInput('name', value)}
      error={Boolean(formError.name)}
      helperText={{formError.name}, `${getString.length}/${CHARACTER_LIMIT}`}
    />

what i want is just like this

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your onChange handler gets the event. You need to get the value out of it.

  1. Update the onHandleChangeInput like below.
const onHandleChangeInput = (field, event) => {
    const { value } = event.target;
    setString({ value: value, length: value.length });
    onHandleInputValidation(field, value);
};
  1. name the parameter as event instead of value to be clear.
onChange={(event) => onHandleChangeInput("name", event)}
  1. Use a ternary to show error message or helperText.
      helperText={
        Boolean(formError.name)
          ? formError.name
          : `${getString.length}/${CHARACTER_LIMIT}`
      }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading