Home » How to Create Image Magnifier in React JS

How to Create Image Magnifier in React JS

how to create image magnifier react js

In today’s blog post, we are going learn how to create an image magnifier in React JS. we will create a simple react component that magnifies the image when the mouse is hovered over the image. Hover effects are a popular way to add interactivity to our websites, and magnifying an image on hover is a great way to highlight details.

How to Magnify Image on Hover in React JS

In the above demo video, we can see that when the user hovers over the image we are magnifying the image details. When the mouse pointer is outside the image area we are hiding the magnifying effect.

Creating ImageMagnifier component

First, we will create a component `ImageMagnifier` that takes `imgUrl` as a prop. Inside the `ImageMagnifier` component, we define three state variables using the useState hook.

const [position, setPosition] = useState({ x: 0, y: 0 });
const [showMagnifier, setShowMagnifier] = useState(false);
const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 });

The `position` state variable stores the x and y coordinates of the mouse over the image, the `showMagnifier` state determines whether the magnifying glass is shown or hidden, and the `cursorPosition` stores the x and y coordinates of the mouse cursor.

Handling the mouse hover on the image

Next, we define a function called `handleMouseHover` that will be called whenever the mouse moves over the image.

const handleMouseMove = (e) => {
  const { left, top, width, height } = e.currentTarget.getBoundingClientRect();
  const x = ((e.pageX - left) / width) * 100;
  const y = ((e.pageY - top) / height) * 100;
  setPosition({ x, y });
  setCursorPosition({ x: e.pageX - left, y: e.pageY - top });
};

The `handleMouseHover` function calculates the position of the mouse over the image and updates the `position` and `cursorPosition` state variables accordingly.

Inside the function, the getBoundingClientRect() method is used to get the dimensions and position of the image element that triggered the event. This information is then used to calculate the mouse’s position relative to the image.

The `x` and `y` coordinates of the mouse are calculated as a percentage of the image’s width and height, respectively, and stored in the `position` state variable.

Additionally, the exact pixel coordinates of the mouse within the image are stored in the `cursorPosition` state variable.

JSX code for image magnifier

Finally, we return the JSX code that renders the image and the magnifying glass.

return (
  <div
    className="img-magnifier-container"
    onMouseEnter={() => setShowMagnifier(true)}
    onMouseLeave={() => setShowMagnifier(false)}
    onMouseMove={handleMouseMove}
  >
    <img className="magnifier-img" src={imgUrl} alt="" />

    {showMagnifier && (
      <div
        style={{
          position: "absolute",
          left: `${cursorPosition.x - 100}px`,
          top: `${cursorPosition.y - 100}px`,
          pointerEvents: "none",
        }}
      >
        <div
          className="magnifier-image"
          style={{
            backgroundImage: `url(${imgUrl})`,
            backgroundPosition: `${position.x}% ${position.y}%`,
          }}
        />
      </div>
    )}
  </div>
);

The above JSX code creates a container `div` with the `img-magnifier-container` class and sets up event listeners for when the mouse enters, leaves, and moves over the image. The `img` tag displays the image specified by the `imgUrl` prop.

When the `showMagnifier` state variable is true, a magnifying glass is displayed using an absolutely positioned `div` with the `magnifier-image` class. The position of this `div` is set to the current cursor position minus 100px to center the magnifying glass over the cursor.

The `backgroundImage` CSS property is set to the `imgUrl` prop, and the `backgroundPosition` property is set to the `position` state variable, which represents the position of the mouse over the image.

Also checkout:

Complete code of ImageMagnifier.js

import React, { useState } from "react";

function ImageMagnifier({ imgUrl }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [showMagnifier, setShowMagnifier] = useState(false);
  const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 });

  const handleMouseHover = (e) => {
    const { left, top, width, height } =
      e.currentTarget.getBoundingClientRect();
    const x = ((e.pageX - left) / width) * 100;
    const y = ((e.pageY - top) / height) * 100;
    setPosition({ x, y });

    setCursorPosition({ x: e.pageX - left, y: e.pageY - top });
  };

  return (
    <div
      className="img-magnifier-container"
      onMouseEnter={() => setShowMagnifier(true)}
      onMouseLeave={() => setShowMagnifier(false)}
      onMouseMove={handleMouseHover}
    >
      <img className="magnifier-img" src={imgUrl} alt="" />

      {showMagnifier && (
        <div
          style={{
            position: "absolute",
            left: `${cursorPosition.x - 100}px`,
            top: `${cursorPosition.y - 100}px`,
            pointerEvents: "none",
          }}
        >
          <div
            className="magnifier-image"
            style={{
              backgroundImage: `url(${imgUrl})`,
              backgroundPosition: `${position.x}% ${position.y}%`,
            }}
          />
        </div>
      )}
    </div>
  );
}

export default ImageMagnifier;

Using the `ImageMagnifier` component in App.js

import React from "react";
import ImageMagnifier from "./ImageMagnifier";

const IMG_URL = "";

function App() {
  return <div>
    <ImageMagnifier imgUrl={IMG_URL} />
  </div>;
}

export default App;

In the above App.js code, we have defined a constant variable `IMG_URL` that contains the image URL. The `imgUrl` prop of the `ImageMagnifier` component is then set to `IMG_URL`, which means that the component will display this image and provide a magnifying effect when the user hovers over it.

Output:

magnify image on hover react js

Conclusion

That’s it, we have created a simple image magnifier or magnifying glass effect using React JS. I hope it was helpful.

Leave a Reply

Your email address will not be published.