0

The file tag where I have declared that only PNG/JPEG files are allowed.

enter image description here

And according to React Dev Tools it is just working fine meant that the file get added successfully.

enter image description here

But when I tried to add file with other extensions other than PNG/JPEG the files are not get added but in the frontend I can see the name of the file.

enter image description here

According to React Dev Tools, File is not get added.

enter image description here

I just wanted, not display the name of the invalidate files like (.pdf, .mp3, etc).

In the Frontend I just wanted to see No File Chosen in place of the Invalidate File name.

Souvik Pal
  • 43
  • 1
  • 5
  • Does this answer your question? [How to reset ReactJS file input](https://stackoverflow.com/questions/42192346/how-to-reset-reactjs-file-input) – Konrad Feb 02 '23 at 15:16
  • 1
    That's not what he's asking. What he wants to achieve is that, when a file is not actually selected, because it's wrong format, the name should not appear in the "Choose file" field. – Jake Feb 02 '23 at 15:18
  • @Sun Yes, you got me right. Any suggestions how to do this? – Souvik Pal Feb 02 '23 at 15:20
  • Does this answer your question? [Limit file format when using ?](https://stackoverflow.com/questions/4328947/limit-file-format-when-using-input-type-file) – matthiasgiger Feb 02 '23 at 15:24
  • @matthiasgiger, even you use this, files with other extensions will be get displayed in the frontend – Souvik Pal Feb 02 '23 at 15:50
  • @SouvikPal take a look at my answer below doing it manually. – matthiasgiger Feb 02 '23 at 16:13

1 Answers1

1

Browser built-in options to manage this are somewhat limited, but you can achieve this by doing it manually like this:

export default function App() {
  return (
    <input
      type="file"
      onChange={(event) => {
        if (!event.target.value.endsWith(".png")) {
          event.target.value = null;
        }
      }}
    />
  );
}

This will reset the input unless the file is a PNG.

matthiasgiger
  • 1,086
  • 9
  • 17