Categories
React Answers

How to display a image selected from file input in React?

Spread the love

Sometimes, we want to display a image selected from file input in React.

In this article, we’ll look at how to display a image selected from file input in React.

How to display a image selected from file input in React?

To display a image selected from file input in React, we can call the URL.createObjectURL with the selected file object to and set the returned value as the value of the src prop of the img element.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [img, setImg] = useState();

  const onImageChange = (e) => {
    const [file] = e.target.files;
    setImg(URL.createObjectURL(file));
  };

  return (
    <div>
      <input type="file" onChange={onImageChange} />
      <img src={img} alt="" />
    </div>
  );
}

We define the img state which we use as the value of the src prop of the img element.

Next, we define the omImageChange function that takes the file from the e.target.files property via destructuring.

Then we call URL.createObjectURL on the file to return a URL that we can use as the value of img.

And we call setImg with the returned URL string to set that as the value of img.

Now when we select an image file, we should be able to see the selected image below the file input.

Conclusion

To display a image selected from file input in React, we can call the URL.createObjectURL with the selected file object to and set the returned value as the value of the src prop of the img element.

By John Au-Yeung

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

2 replies on “How to display a image selected from file input in React?”

Leave a Reply

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