1

Overview

In my pursuit to optimize my web appliations, I am transitioning from standard img tags to Next's Image tag. While it is great for performance, making it do custom effects and styling can be frustrating.

The Problem

I am trying to add a parallax effect to a Next Image. I was previously able to add a parallax library but that seemed to not integrate with the Image tag.

Is there a way to add a simple parallax effect on scroll to a Next image?

My Attempts

  1. I've tried adding a dynamic translateY style property to the Image tag itself, but the browser doesn't seem to read the string interpolation.
<Image
  src={url}
  height={450}
  width={1080}
  layout="responsive"
  className="object-cover"
  style={{transform: 'translateY(${offset / 2}px)'}}
/>

Here is a repl.it link that you can look at.

Tyler Morales
  • 1,440
  • 2
  • 19
  • 56

1 Answers1

1

This one is interesting as there is no ref returned, however you can assign it a className and access the element, here is one way to do it

via the documentation:

Target the image with className, not based on DOM structure

Regardless of the layout mode used, the Image component will have a consistent DOM structure of one tag wrapped by exactly one . For some modes, it may also have a sibling for spacing. These additional elements are critical to allow the component to prevent layout shifts.

The recommended way to style the inner is to set the className prop on the Image component to the value of an imported CSS Module. The value of className will be automatically applied to the underlying element.

I used a popular tiny parallax library called rellax and passed the image to it.

https://codesandbox.io/s/next-import-svg-forked-37i7h?file=/pages/index.js&resolutionWidth=320&resolutionHeight=675

You can see the result here - https://37i7h.sse.codesandbox.io/ - it's not a complete parallax display but you can see the library correctly applies translate params to the img.

Ramakay
  • 2,919
  • 1
  • 5
  • 21