Passing string array to Next.js Image component

Geminijefferson nwadi
Sign in to confirm0 confirmations

Question

The Next.js Image component expects a single string or StaticImport, but is being passed a string array. The goal is to display a product card with hover-swap functionality.

Answer

To fix the type error, extract the ProductCard as a proper named component to obey the Rules of Hooks. Then, use the useState hook within this component to handle the hover state, switching between the first and second images in the array. This ensures that the Image component always receives a single string.

tsx
<Image src={product.images} />
tsx
const [hover, setHover] = useState(false);
tsx
onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
typescriptreactnextjshooks