menu

Questions & Answers

Setting the value of a MUI file TextField causes an exception

I"m trying to set the value of a MUI Textfield that has type="file" props,
and this exception appears in the console:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
Only an empty string doesn't causing this exception.

Here is my component:

const MyComponent = () => {
  const [image, setImage] = useState("");

  const handleImageChange = (event) => {
    event.preventDefault();
    let reader = new FileReader();
    let file = event.target.files[0];
    reader.onloadend = () => {
      setImage(reader.result);
    };
    reader.readAsDataURL(file);
  };

  return (
    <TextField
      helperText="Cover photo"
      type="file"
      value={image}
      onChange={handleImageChange}
    />
  );
};

I tried to simplify the component (still same exception):

<TextField type="file" value={"https://www.someSite.com/image.jpg"} />

Also, I tried to set the value of the input itself using InputProps, still the same exception.

According to MUI Docs value could be 'any' regardless the type: MUI Docs

Comments:
2023-01-17 23:25:03
Maybe this link has your solution stackoverflow.com/questions/40589302/…
2023-01-17 23:25:03
I saw this one before I posted my question, but the solutions they offered are different from what I"m trying to do: to upload an image and display the url as string - the same functionality as a regular HTML input
Answers(0) :