Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error.

TypeError: Failed to construct 'Image': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

Here is the modified code snippet:

import React, { useState, useRef, useEffect } from "react";

const ImageUploadCard = () => {
  const componentRef = useRef(null);
  const [componentWidth, setComponentWidth] = useState(0);
  const [componentHeight, setComponentHeight] = useState(0);

  useEffect(() => {
    // Function to update component width
    function updateComponentWidth() {
      if (componentRef.current) {
        const width = componentRef.current.getBoundingClientRect().width;
        const height = componentRef.current.getBoundingClientRect().height;

        console.log("Component width:", width);
        console.log("Component width:", height);
        setComponentWidth(width);
        setComponentHeight(height);
      }
    }

    // Update component width initially and add event listener for window resize
    updateComponentWidth();
    window.addEventListener("resize", updateComponentWidth);

    // Clean up event listener on component unmount
    return () => {
      window.removeEventListener("resize", updateComponentWidth);
    };
  }, []);

  const inputRef = useRef(null);
  const [previewImage, setPreviewImage] = useState(null);

  const handleImageChange = (event) => {
    const file = event.target.files[0];
    if (file && file.size > 5242880) {
      // File size exceeds the maximum limit
      // You can display an error message or handle it as needed
      console.log("File size exceeds the maximum limit (5MB)");

      return;
    }
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewImage(reader.result);
      };
      reader.readAsDataURL(file);
    } else {
      setPreviewImage(null);
    }
  };

  return (
    <div ref={componentRef} className="mb-6 md:pr-2">
      <div
        style={{ width: componentWidth }}
        className="dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center"
        onClick={() => inputRef.current.click()} // Click event triggers file input
      >
        <div className="relative z-10 cursor-pointer">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 24 24"
            width="24"
            height="24"
            className="fill-jacarta-500 mb-4 inline-block dark:fill-white"
          >
            <path fill="none" d="M0 0h24v24H0z" />
            <path d="M16 13l6.964 4.062-2.973.85 2.125 3.681-1.732 1-2.125-3.68-2.223 2.15L16 13zm-2-7h2v2h5a1 1 0 0 1 1 1v4h-2v-3H10v10h4v2H9a1 1 0 0 1-1-1v-5H6v-2h2V9a1 1 0 0 1 1-1h5V6zM4 14v2H2v-2h2zm0-4v2H2v-2h2...
          </svg>
          <p className="dark:text-jacarta-300 mx-auto max-w-xs text-xs">
            Image formats: JPEG, PNG, JPG . Max size: 5 MB
          </p>
          <label>
            <input
              type="file"
              accept=".jpg, .jpeg, .png"
              onChange={handleImageChange}
              style={{ display: "none" }} // Hide the input visually
              ref={inputRef}
              // Set a max file size of 5MB (in bytes)
              // 5MB = 5 * 1024 * 1024 bytes
              // Adjust this value as needed
              max="5242880"
            />
          </label>
        </div>
      </div>

      {previewImage && (
        <div
          className="dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center"
          style={{ width: componentWidth, height: 400 }} // Set width dynamically
        >
          <Image
            src={previewImage}
            alt="Preview"
            style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "cover" }}
          />
        </div>
      )}
    </div>
  );
};

export default ImageUploadCard;

The current working <img> tag implementation:

import React, { useState, useRef, useEffect } from "react";

const ImageUploadCard = () => {
  const componentRef = useRef(null);
  const [componentWidth, setComponentWidth] = useState(0);
  const [componentHeight, setComponentHeight] = useState(0);

  useEffect(() => {
    // Function to update component width
    function updateComponentWidth() {
      if (componentRef.current) {
        const width = componentRef.current.getBoundingClientRect().width;
        const height = componentRef.current.getBoundingClientRect().height;

        console.log("Component width:", width);
        console.log("Component width:", height);
        setComponentWidth(width);
        setComponentHeight(height);
      }
    }

    // Update component width initially and add event listener for window resize
    updateComponentWidth();
    window.addEventListener("resize", updateComponentWidth);

    // Clean up event listener on component unmount
    return () => {
      window.removeEventListener("resize", updateComponentWidth);
    };
  }, []);

  const inputRef = useRef(null);
  const [previewImage, setPreviewImage] = useState(null);

  const handleImageChange = (event) => {
    const file = event.target.files[0];
    if (file && file.size > 5242880) {
      // File size exceeds the maximum limit
      // You can display an error message or handle it as needed
      console.log("File size exceeds the maximum limit (5MB)");

      return;
    }
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewImage(reader.result);
      };
      reader.readAsDataURL(file);
    } else {
      setPreviewImage(null);
    }
  };

  return (
    <div ref={componentRef} className="mb-6 md:pr-2">
      <div
        style={{ width: componentWidth }}
        className="dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center"
        onClick={() => inputRef.current.click()} // Click event triggers file input
      >
        <div className="relative z-10 cursor-pointer">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 24 24"
            width="24"
            height="24"
            className="fill-jacarta-500 mb-4 inline-block dark:fill-white"
          >
            <path fill="none" d="M0 0h24v24H0z" />
            <path d="M16 13l6.964 4.062-2.973.85 2.125 3.681-1.732 1-2.125-3.68-2.223 2.15L16 13zm-2-7h2v2h5a1 1 0 0 1 1 1v4h-2v-3H10v10h4v2H9a1 1 0 0 1-1-1v-5H6v-2h2V9a1 1 0 0 1 1-1h5V6zM4 14v2H2v-2h2zm0-4v2H2v-2h2zm0-4v2H2V6h2zm0-4v2H2V2h2zm4 0v2H6V2h2zm4 0v2h-2V2h2zm4 0v2h-2V2h2z" />
          </svg>
          <p className="dark:text-jacarta-300 mx-auto max-w-xs text-xs">
            Image formats: JPEG, PNG, JPG . Max size: 5 MB
          </p>
          <label>
            <input
              type="file"
              accept=".jpg, .jpeg, .png"
              onChange={handleImageChange}
              style={{ display: "none" }} // Hide the input visually
              ref={inputRef}
              // Set a max file size of 5MB (in bytes)
              // 5MB = 5 * 1024 * 1024 bytes
              // Adjust this value as needed
              max="5242880"
            />
          </label>
        </div>
      </div>

      {previewImage && (
        <div
          className="dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center"
          style={{ width: componentWidth, height: 400 }} // Set width dynamically
        >
          <img
            src={previewImage}
            alt="Preview"
            style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "cover" }}
          />
        </div>
      )}
    </div>
  );
};

export default ImageUploadCard;

Desiring to replace the existing <img> tag with the latest version of the Image component while maintaining the same functionality.

Answer №1

Make sure to include the Image component in your code by adding this line:

import Image from "next/image";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while attempting to install material-ui v3.0.3 due to an unexpected termination of the JSON input

I'm currently in the process of installing the most recent stable version of material-ui(v3.03) by running: npm install @material-ui/core. However, I encountered an issue with npm ERR! Unexpected end of JSON input while parsing near '...-/brcast- ...

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...

Ajax is known for inundating servers with requests at a rapid rate, causing a significant

I am running an application that sends multiple requests per second to fetch data from API and return responses to clients. The process flow is as follows: Ajax sends a request View sends a request API returns response for view View returns response for ...

Is there a way to retrieve the same post from one controller and access it in another?

Hello, I am currently exploring the world of Full Stack web development and have stumbled upon a challenge. My tech stack includes mongodb, mongoose, node, and express. Within my project, I have implemented two controllers - one for user signup and anothe ...

How come the error message in AngularJS is appearing as blank during error handling?

When utilizing AngularJS code to send a request to the server, everything works smoothly on success. However, deliberately redirecting the request to a different domain causes the CORS problem where the error handling function is triggered but errorData ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

Vue.js: In a third-party library, the reference to "this" is coming back as "undefined"

My third-party script contains code in the following format ( function initialMethod(scope, factory) { // 'scope' is undefined when used in Vue // but it works fine in React and Angular } (this, function function1(param1) { ...

Header-driven redirection

I am using node js and express js. My goal is to ensure that if app.get does not have a token parameter, then an html file with js will be uploaded to pass the token. If the token is passed, then another html file should be displayed. However, I am unsure ...

Encountering a 401 Error while using Laravel Sanctum/Airlock

Currently, I am utilizing Laravel as the back-end for my innovative Next JS application, with Sanctum being leveraged for authentication purposes. While session authentication operates smoothly on the front end, issues arise when attempting to send reque ...

Is it possible to implement MV* in Polymer using models and services as polymer elements?

Imagine I want two views (polymer-elements) to share a model, how can this be achieved? In Angular, the model would reside in a singleton service that is injected into the views, allowing both views to access the same data source. I attempted to replicat ...

Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows: {"<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Error encountered in React Material UI: Appbar - TypeError occurred when attempting to read properties that are undefined (specifically, reading '100')

Currently, I am working on developing a multi-step form using Material UI components. However, upon importing the necessary components, an error is being displayed in my code snippet: import React from 'react'; import { ThemeProvider } from &a ...

Leverage information stored in an array within the HandsonTable Angular directive

Some of my columns in a HandsoneTable created using Angular directives are not rendering when I try to use an array as the data source with common array notation (name[0]). I'm unsure if this is supposed to work like this or if I am doing something wr ...

Modify the height of an element in real-time using jQuery

I'm looking to dynamically adjust the height of a div based on another element, but only if that element does not have the class collapsed (which is used in a Bootstrap toggle collapse feature). The initial setup seems to work fine, however, when I i ...

I am having trouble with the hover feature on the image tag. Does anyone know how to troubleshoot this issue?

h1{ color:red; font-size: 100px; } img :hover { background-color: gold; } .bacon{ background-color: green; } .broccoli{ background-color: red; } /* .circular{ border-radius: 100%; } */ #heading{ background-color: aquamarine; ...

When using angularjs, the $window.location.href may cause the page to load without any

I have a dilemma where I have linked all my CSS and JS files in the index.html file, but subpages are located in a templates directory. When using $window.location.href, only a plain HTML page is returned without any CSS styles. The page renders fine when ...

Bidirectional Communication between ExpressJS and Mongoose Models

Let's consider a scenario where we have a User model and a Book model in our express app, both referencing each other. How can mongoose middleware be utilized to ensure that both models stay synchronized when saving either one? It would be beneficial ...

Link a PHP variable to a JavaScript variable

Is there a way to set the value of a JavaScript variable using a PHP variable? $(function(){ $("select[name=myselectlist]").change(function(){ var id = $(this).val(); if(id != 0) { $.post("ajax.php", {"id":id}, func ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

The parent node is returning a child element

Currently working on a website using Vue 3.0 and Element+ and encountering an inconsistency. There is a div displayed on the page (an array of objects) and the goal is to remove the object from the array when a button is clicked. The issue arises when som ...