Skip to content
Advertisement

How do I handle undefined state in react when the user hits cancel on file selection?

I have a simple Input type= file. I am capturing the the selected file in state. Once a file is selected and the clear button is clicked it does not clear the state. This causes

{selectedFile.name}

to throw an undefined error when the user clicks cancel during the next file selection.

Is there a way to make my clear button actually clear selectedFile state? or a way to handle the error so that a file can still be selected?

JavaScript

enter image description here

Advertisement

Answer

First You need to set the default null value to selectedFile state.

JavaScript

Then, in handleClear Function set,

JavaScript

and final the condition should be

JavaScript

[optional]: the default file select event does not select the same file again, so if you need to allow the user to select the same file then add following property in the input tag:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement