React Image Preview - JavaScript Exercise #13

React Image Preview - JavaScript Exercise #13

Build a React Image Preview Component

ยท

6 min read

Overview

In this exercise, you will build a React component that allows users to preview images before uploading them. The component will display a thumbnail preview of the selected image and provide users with the option to remove the image.

Instructions

  1. Create a new React component called ImagePreview.

  2. Define the component's state to include a property called 'imageUrl' and set its initial value to an empty string.

  3. Add an input element to the component that allows users to select an image file.

  4. Add an onChange event handler to the input element that sets the state's 'imageUrl' property to the URL of the selected image.

  5. Use the 'imageUrl' property to display a thumbnail preview of the selected image.

  6. Add a button that allows users to remove the selected image.

  7. Add an onClick event handler to the remove button that sets the state's imageUrl property back to an empty string.

  8. Style the component using CSS to make it visually appealing.

Bonus Requirements

  1. Allow users to preview multiple images at once.

  2. Add a feature that displays the image's name and size next to the thumbnail preview.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Image Preview exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Implementation of the React Image Preview Component exercise

import React, { useState } from 'react';

function ImagePreview() {
  const [imageUrl, setImageUrl] = useState('');

  const handleImageChange = (event) => {
    const file = event.target.files[0];
    const url = URL.createObjectURL(file);
    setImageUrl(url);
  };

  const handleRemoveImage = () => {
    setImageUrl('');
  };

  return (
    <div>
      <input type="file" onChange={handleImageChange} />
      {imageUrl && (
        <div>
          <img src={imageUrl} alt="preview" />
          <button onClick={handleRemoveImage}>Remove</button>
        </div>
      )}
    </div>
  );
}

export default ImagePreview;

This implementation allows users to select an image file, displays a thumbnail preview of the selected image, and provides a button to remove the image. Note that this implementation only allows users to preview one image at a time.

here's an updated implementation of the ImagePreview component that only allows PNG and JPEG files, displays an error message for unsupported files and sets the accept attribute on the input element to only allow image files:

import React, { useState } from 'react';

function ImagePreview() {
  const [imageUrl, setImageUrl] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  const handleImageChange = (event) => {
    const file = event.target.files[0];
    if (file.type === 'image/png' || file.type === 'image/jpeg') {
      const url = URL.createObjectURL(file);
      setImageUrl(url);
      setErrorMessage('');
    } else {
      setImageUrl('');
      setErrorMessage('Only PNG and JPEG files are supported');
    }
  };

  const handleRemoveImage = () => {
    setImageUrl('');
    setErrorMessage('');
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleImageChange} />
      {errorMessage && <div>{errorMessage}</div>}
      {imageUrl && (
        <div>
          <img src={imageUrl} alt="preview" />
          <button onClick={handleRemoveImage}>Remove</button>
        </div>
      )}
    </div>
  );
}

export default ImagePreview;

This updated implementation sets the accept attribute on the input element to only allow image files. In the handleImageChange function, the file type is checked to make sure it is either a PNG or JPEG file. If it is not, an error message is displayed instead of the image preview. The handleRemoveImage function also clears the error message when the image is removed.

here's an updated implementation of the ImagePreview component that allows users to preview multiple images at once and displays the image's name and size next to the thumbnail preview:

import React, { useState } from 'react';

function ImagePreview() {
  const [imageUrls, setImageUrls] = useState([]);
  const [errorMessage, setErrorMessage] = useState('');

  const handleImageChange = (event) => {
    const files = event.target.files;
    const allowedTypes = ['image/png', 'image/jpeg'];
    const urls = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (allowedTypes.includes(file.type)) {
        const url = URL.createObjectURL(file);
        urls.push({ url, name: file.name, size: file.size });
      } else {
        setErrorMessage(`File '${file.name}' is not a valid image file`);
      }
    }

    setImageUrls((prevUrls) => [...prevUrls, ...urls]);
  };

  const handleRemoveImage = (index) => {
    setImageUrls((prevUrls) => prevUrls.filter((_, i) => i !== index));
    setErrorMessage('');
  };

  return (
    <div>
      <input type="file" accept="image/*" multiple onChange={handleImageChange} />
      {errorMessage && <div>{errorMessage}</div>}
      <div>
        {imageUrls.map((image, index) => (
          <div key={index}>
            <img src={image.url} alt={image.name} />
            <div>
              <div>{image.name}</div>
              <div>{image.size} bytes</div>
            </div>
            <button onClick={() => handleRemoveImage(index)}>Remove</button>
          </div>
        ))}
      </div>
    </div>
  );
}

export default ImagePreview;

This updated implementation adds support for multiple image uploads by setting the multiple attribute on the input element. The handleImageChange function loops through all selected files checks their file type and creates URLs for the valid image files. The URLs, along with the image name and size, are then added to the imageUrls state array.

The thumbnail previews for each image, along with their name and size, are displayed using a map function on the imageUrls array. When the Remove button is clicked, and the corresponding image and its details are removed from the imageUrls array. If an invalid image file is detected during the upload process, an error message is displayed for that file.

Overall, this updated ImagePreview component allows users to upload and preview multiple image files at once and provides additional details for each image.

import React from 'react';
import ImagePreview from './components/ImagePreview';

function App() {
  return (
    <div>
      <h1>React Image Preview Component</h1>
      <ImagePreview />
    </div>
  );
}

export default App;

The ImagePreview component can be used in any React application that requires a user to select and preview image files. Here are some examples of applications where this component could be useful:

  1. Social media platforms: Social media platforms such as Facebook, Twitter, and Instagram allow users to upload images. The ImagePreview component can be used to allow users to preview their selected images before posting them.

  2. E-commerce websites: E-commerce websites often require users to upload product images. The ImagePreview component can be used to allow users to preview their product images before submitting them.

  3. Online art galleries: Online art galleries often require users to upload images of their artwork. The ImagePreview component can be used to allow artists to preview their artwork images before submitting them.

  4. Online education platforms: Online education platforms often require users to upload images as part of their coursework. The ImagePreview component can be used to allow students to preview their images before submitting them.

  5. Photography websites: Photography websites often require users to upload images for portfolios or galleries. The ImagePreview component can be used to allow photographers to preview their images before publishing them.

These are just a few examples of applications where the ImagePreview component could be used. In general, any application that requires users to upload and preview image files can benefit from this component.

In conclusion, the ImagePreview component is a useful tool for React developers who need to allow users to select and preview image files. With this component, users can see a thumbnail of the selected image and remove it if necessary. Additionally, the component can be customized to only allow specific file types and display error messages for unsupported files. The ImagePreview component can be used in a variety of applications, including social media platforms, e-commerce websites, and online art galleries, to name a few. As with any React component, developers should test and modify the ImagePreview component to meet the specific needs of their application.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย