Categories
React Answers

How to hold file input’s value in React?

Spread the love

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

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

How to hold file input’s value in React?

To hold file input’s value in React, we can store the selected file in a state.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [file, setFile] = useState();

  const handleChange = (e) => {
    const [f] = e.target.files;
    setFile(f);
  };

  console.log(file);

  return (
    <div>
      <input onChange={handleChange} multiple={false} type="file" />
    </div>
  );
}

We create the file state with the useState hook.

Then we add the handleChange function that gets the selected file from the e.target.files file list object property.

Then we call setFile with f to set f as file‘s value.

Now when we select a file, we should see file‘s value logged in the console log.

Conclusion

To hold file input’s value in React, we can store the selected file in a state.

By John Au-Yeung

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

Leave a Reply

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