score:-1

If you want to fire the onChange event each time you select a file (regardless of whether it is the same file or a different one) you could set value={''} in your input. This will empty the input every time it is rendered.

I drew inspiration for this answer from chrisv here:

React controlled component input value with empty string

See example below:

import * as React from "react";
import {useEffect, useState} from "react";

const FileComponentTest = () => {
  const [file, setFile] = useState(null);

  useEffect(() => {
    console.log("File has been set.")
  },[file]);

  return (
    <React.Fragment>
      <input
        type="file"
        onChange= {(e) => setFile(e.target.files[0])}
        value ={""}
      />
    </React.Fragment>
  )
};

I get no errors in the console with this.

Update:

Please see link to fiddle below:

https://jsfiddle.net/geoj12/tjbvpyzs/11/

score:18

From the React documentation on uncontrolled elements:

In React, an <input type="file" /> is always an uncontrolled component because its value can only be set by a user, and not programmatically.

This is a security feature, to ensure that you can not pull data from a users disk without them specifically choosing to do so.

To me, it seems like this isn't what you're trying to do. All you want to do is display the name of the selected file. You can do that by creating your own label and button, with a hidden file element. When you click your custom button, call the click event imperatively on the HTMLFileInput. Register your change event on the file input, and update your custom element with the response.


Related Query

More Query from same tag