'how to set value in react input field type file using react bootstrap?

I am using react bootstrap in my demo application . I want to set the value in input type file . also I want to remove the value from input type file field after 10 sec (if there is any value) . is it possible ?

I tried like this

const [val, setValue] = useState("");
  useEffect(() => {
    setTimeout(() => {
      setValue("");
    }, 10000);
  }, []);
  const onchange = (e) => {
    setValue(e.target.value);
  };

HTML

<Form>
        <Form.Group controlId="formFile" className="mb-3">
          <Form.Label>Default file input example</Form.Label>
          <Form.Control type="file" value={val} onchange={onchange} />
        </Form.Group>
      </Form>

here is my whole code https://codesandbox.io/s/react-bootstrap-form-forked-i3zdo5?file=/src/index.js:451-686

my selection of file is not working after adding value={val}



Solution 1:[1]

You need to update your onchange function to something like :

const onchange = (e) => {
    setValue(e.target.files[0]);
  };

Your onchange function works fine for text inputs (and some others), but will fails when input type is file. You need t make sure to look what kind of event is being returned before processing it, as these events depends on type of elements they are generated from & cause of event.

Edit : value does not work on file input element, you can only set it programmatically to empty string. Maybe try using ref to clear the input being selected.

Solution 2:[2]

first thing ,you can't set value of input type file ,so assigning a value is not a good idea,and if you want to clear its if user selected any file,then you need to do two things

1.create ref to point input type file and assing it to component ref prop

const fileInputRef = useRef();

and in render method use it like this

      <Form.Control ref={fileInputRef} type="file" onChange={onchange} />

also you need to change onchange to onChange in react

  1. in side your useEffect call back ,you will need to add dependencies and set timeout like this

    useEffect(() => {
    setTimeout(() => {
     if (val !== "") {
    fileInputRef.current.value = "";
    setValue("");
      }
    }, 10000);
     }, [setValue, val]);
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jatin Parmar