To create image zoom effects using the useHover
hook in Next.js, you can follow these steps:
useHover
hook. If you haven't already installed them, you can do so using npm or yarn:bashnpm install react next react-dom
npm install use-hover
or
bashyarn add react next react-dom
yarn add use-hover
useHover
to track mouse hover state:javascript// useHover.js
import { useState } from 'react';
import useHover from 'use-hover';
function useImageZoom() {
const [isHovered, bind] = useHover();
const [zoomed, setZoomed] = useState(false);
const handleZoom = () => {
setZoomed(true);
};
const handleUnzoom = () => {
setZoomed(false);
};
return {
isHovered,
bind,
zoomed,
handleZoom,
handleUnzoom,
};
}
export default useImageZoom;
javascript// ImageZoom.js
import React from 'react';
import useImageZoom from './useImageZoom';
const ImageZoom = ({ src }) => {
const { isHovered, bind, zoomed, handleZoom, handleUnzoom } = useImageZoom();
return (
<div {...bind}>
<img
src={src}
alt="Zoomable Image"
onMouseEnter={handleZoom}
onMouseLeave={handleUnzoom}
style={{
width: zoomed ? '200%' : '100%',
transition: 'width 0.5s',
cursor: isHovered ? 'zoom-in' : 'auto',
}}
/>
</div>
);
};
export default ImageZoom;
ImageZoom
component in your Next.js application:javascript// pages/index.js
import React from 'react';
import ImageZoom from '../components/ImageZoom';
const Home = () => {
return (
<div>
<h1>Image Zoom Effect Example</h1>
<ImageZoom src="/example-image.jpg" />
</div>
);
};
export default Home;
Replace /example-image.jpg
with the path to your image.
Now, when you hover over the image, it will zoom in, and when you move the mouse away, it will zoom out. Adjust the styling and transition timings as needed to achieve the desired effect.