How to show Image upload preview

How to show Image upload preview

ยท

2 min read

Hey All ๐Ÿ‘‹๐Ÿ‘‹๐Ÿ‘‹

In this article, I am about to discuss something that was given to me as part of my interview task. Which was to create a preview of the picture before it is uploaded. So let's start.


Here, I have used a React application. After clearing the app.js file, the code now looks like this:

export default function App() {
  return (
    <div className="App">
    </div>
  );
}

Then I added a header and a div which will contain input and an image:

export default function App() {
  return (
    <div className="App">
      <h1>Image Upload Preview</h1>
      <div className="imageContainer">
      </div>
    </div>
  );
}

After that, I added the styles:

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Image Upload Preview</h1>
      <div className="imageContainer">
      </div>
    </div>
  );
}
.App {
  font-family: sans-serif;
  text-align: center;
}

.imageContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

Then I added an input for uploading the picture and used a state to store it:

import "./styles.css";
import { useState } from "react";

export default function App() {
const [image, setImage] = useState(null);

const handleImageUpload = (e) => {
    setImage(URL.createObjectURL(e.target.files[0]));
  };

  return (
    <div className="App">
      <h1>Image Upload Preview</h1>
      <div className="imageContainer">
          <input type="file" accept="image/*" onChange={handleImageUpload} />
      </div>
    </div>
  );
}

Note: The URL.createObjectURL() static method creates a string containing a URL representing the object given in the parameter. Read more ->

Now the page would look something like this:

preview

Lastly, I displayed the image if it existed and added styles:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [image, setImage] = useState(null);

  const handleImageUpload = (e) => {
    setImage(URL.createObjectURL(e.target.files[0]));
  };
  return (
    <div className="App">
      <h1>Image Upload Preview</h1>
      <div className="imageContainer">
        <input type="file" accept="image/*" onChange={handleImageUpload} />
        {image ? <img src={image} className="image" alt="preview" /> : null}
      </div>
    </div>
  );
}
.App {
  font-family: sans-serif;
  text-align: center;
}

.imageContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image {
  height: 200px;
  width: 200px;
  margin-top: 20px;
  border: 1px solid black;
  border-radius: 5px;
}

The final result after uploading a picture:

preview

Link to code-sandbox ->


Thanks for reading. Have a nice day. ๐Ÿ™‚

Let's connect - ๐Ÿ‘‹๐Ÿ‘‹๐Ÿ‘‹

ย