'How to update image source on hover?
I'm trying to use Next.js Image component to render images on my app page. I'm having issues understanding how to select and update the main Image src so that I can replace it with all the responsive sizes Next.js creates for Image elements.
I have a list of navigation links in my app menu and I want to assign data attributes to each one so that when these links are hovered over they update the main Image element and display a different main image for each link hovered over.
I'm new to React and the way it works, so I'm not sure what my issues are but I have made a start with some basic concepts. I have started to console log the data I have to see what I get but now I've hit a brick wall.
Here is what I have so far:
import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
function Header() {
const MenuHeroImg = useRef();
function handleMouseEnter(e) {
console.log(e.target.getAttribute('data-project-image-url'));
console.log(MenuHeroImg.current);
}
return (
<>
<ul>
<li
onMouseEnter={handleMouseEnter}
data-project-image-url="/public/images/projects/image_2.png"
className={`${navigationStyles['c-navigation-menu-link']}`}>
<Link href="/project-link-here">Link</Link>
</li>
<li
onMouseEnter={handleMouseEnter}
data-project-image-url="/public/images/projects/image_3.png"
className={`${navigationStyles['c-navigation-menu-link']}`}>
<Link href="/project-link-here_2">Link</Link>
</li>
<ul>
<picture ref={MenuHeroImg}>
<Image
src="/public/images/projects/image_1.png"
alt="Image"
width={660}
height={835}
layout="responsive"
/>
</picture>
</>
);
}
export default Header;
Solution 1:[1]
the src should be like this:/images/projects/image_1.png; because nextjs look for the image in the root folder that is the public folder
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Navidi |

