How to allow input type=file to select the same file in a React component?

Sometimes, we want to allow input type=file to select the same file in a React component.

In this article, we’ll look at how to allow input type=file to select the same file in a React component.

How to allow input type=file to select the same file in a React component?

To allow input type=file to select the same file in a React component, we set the file selection to null after we click on the file input button.

For instance, we write

const Comp = () => {
  //...

  return (
    <input
      id="upload"
      ref="upload"
      type="file"
      accept="image/*"
      onInput={(event) => {
        readFile(event);
      }}
      onClick={(event) => {
        event.target.value = null;
      }}
    />
  );
};

to add a file input.

We set the onInput prop to a function that calls readFile to get the file.

And we set the onClick prop to a function that sets event.target.value to null so we can select the same file again.

Conclusion

To allow input type=file to select the same file in a React component, we set the file selection to null after we click on the file input button.