Categories
React Answers

How to Put a File in a State Variable with React Hooks?

Spread the love

Sometimes, we want to put a file in a state variable with React Hooks.

In this article, we’ll look at how to put a file in a state variable with React Hooks.

Put a File in a State Variable with React Hooks

We can put a file in a state variable with the useState hook.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [picture, setPicture] = useState([]);
  console.log(picture);

  return (
    <div className="App">
      <input
        type="file"
        onChange={(e) => {
          const [file] = e.target.files;
          setPicture((picture) => [...picture, file]);
        }}
      />
    </div>
  );
}

We define the picture state with the useState hook.

Then we add a file input by setting the type attribute of the input to file .

And then we add an onChange callback that takes the selected file from e.target.files with destructuring.

Then we call setPicture with a callback that takes the existing picture state value and return a new array with the picture items spread into it and the newly selected file .

Now when we select files with the file input, pictures should log an array with all the selected files.

Conclusion

We can put a file in a state variable with the useState hook.

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 *