Categories
React Answers

How to Reset a File Input’s Value in React?

Spread the love

Sometimes, we want to reset a file input’s value in React.

In this article, we’ll look at how to reset a file input’s value in React.

Reset a File Input’s Value in React

To reset a file input’s value in React, we can set the value property of the file input to an empty string.

For instance, we can write:

import React, { useRef } from "react";

export default function App() {
  const ref = useRef();

  const reset = () => {
    ref.current.value = "";
  };

  return (
    <>
      <input type="file" ref={ref} />
      <button onClick={reset}>reset</button>
    </>
  );
}

We call the useRef hook to create a ref object.

And we assign that to the file input with the ref prop.

Next, we add a button that calls the reset function when we click it.

And in the reset function, we set ref.current.value to an empty string.

ref.current is the file input element since we passed ref to the ref prop.

Conclusion

To reset a file input’s value in React, we can set the value property of the file input to an empty string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Reset a File Input’s Value in React?”

This approach doesn’t work. Even if current.value is set to an empty string, the actual contents of the input type file are stored in current.files; The current.files return a File object which itself is immutable. I’m currently trying to find a way to actually remove this file from current.files, so if you have any tips I’d be very grateful.

The code just clears the file input display. You should keep track of the files in its own state instead of relying on the files property.

Leave a Reply

Your email address will not be published. Required fields are marked *