Home > other >  Reactjs TextField helperText
Reactjs TextField helperText

Time:02-23

how can I synchronize error validation with the character limit without affecting its functions, please see this enter image description here

CodePudding user response:

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}`
      }

CodePudding user response:

import React, { useState } from "react";
import { TextField } from "@mui/material";
import "./styles.css";

export default function App() {
  const CHARACTER_LIMIT = 1000;
  const [getString, setString] = useState({
    value: "",
    length: 0
  });
  const onHandleChangeInput = (field, value) => {
    const { value: inputValue } = value.target;
    setString({ value: inputValue, length: inputValue.length });
  };
  return (
    <TextField
      label="Name"
      inputProps={{
        maxLength: CHARACTER_LIMIT
      }}
      values={getString.value}
      onChange={(e) => onHandleChangeInput("name", e)}
      error={Boolean(getString.length === CHARACTER_LIMIT)}
      helperText={`${getString.length}/${CHARACTER_LIMIT}`}
    />
  );
}

you are not using value from onChange as you were sending event then I extracted that value for you. Take a look

CodePudding user response:

You cannot exceed the charachter limit as long as you have not removed inputProps={{ maxLength: CHARACTER_LIMIT }}, after that you could use Edit mui FormHelperText two messages

  • Related