I am new to both MUI and React, but in an effort to keep smaller stuff off our overworked devs’ plates, I’m tackling a couple of things. One of those is: I’m attempting to retroactively add some descriptive helperText to a few fields. At present, we’re already set up for error helperText; I need to be able to do this without taking away that capability.
Here’s our current FormInputText.tsx:
import { Controller } from "react-hook-form";
import TextField from "@mui/material/TextField";
import { FormInputProps } from "./FormInputProps";
import { FormHelperText } from "@mui/material";
export const FormInputText = ({
name,
control,
label,
required = false,
type = "text",
disabled = false,
big = false,
score = false,
}: FormInputProps) => {
return (
<Controller
name={name}
control={control}
render={({
field: { onChange, value },
fieldState: { error },
formState,
}) => {
return (
<TextField
style={{ marginBottom: "25px" }}
helperText={error ? error.message : null}
size={!big ? "small" : "medium"}
error={!!error}
onChange={onChange}
fullWidth
label={label}
variant="outlined"
value={value}
required={required}
type={type}
disabled={disabled}
/>
);
}}
/>
);
};
How can I modify this to allow non-error-type helperText?
Many thanks in advance!
2
Answers
Currently you show helperText only if error is true, and you can pass one more prop to
FormInputText
calledhelperText = ""
(by default), and replace your code fromhelperText={error ? error.message : null}
tohelperText={error ? error.message : helperText}
. So now if you pass helperText prop toFormInputText
, and error is false, it will display it.To add non-error-type helper text to your FormInputText component, you can use FormHelperText from
Material-Ui
here is your modified codeAs you can see in this modificated code, I added a new prop helperText to the component. Now, you can pass the non-error helper text when using the FormInputText component. If the error is present, it will display the error message otherwise, it will display the helperText prop.