Ways to animate elements while scrolling in React.js?

I am new to using React.JS and currently working on setting up an E-commerce Store. My goal is to have 5 images stack on top of each other and move together as the user scrolls. I used to achieve this effect in Vanilla JavaScript by adding a window.addEventListener('scroll') and then adjusting the image position based on scrollY value.

However, I'm unsure how to implement this in React. Should I use a state or useEffect? Where should I set the window event listener?

I have included an image for reference:

https://i.stack.imgur.com/z5ECx.png

In my React setup, I have a component called "Scroll" which includes 2 divs:

- One div on the left (2/3 flex size) containing all 5 stacked images - Another div on the right (1/3 flex size) with text and a button

The left div houses the 5 images positioned on top of each other using CSS's absolute positioning (as they are PNGs with transparent backgrounds).

Any advice on how to execute this smoothly on my website would be greatly appreciated!

Thank you so much in advance!

Answer №1

To optimize your website's performance, consider storing the scrollY position in a useState hook and using it to dynamically transform your images. You can add window event listeners inside a useEffect hook like this:

const [scrollPosition, setScrollPosition] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollPosition(window.scrollY);
    };
    handleScroll();

    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

(Make sure to check if any ESLint rules need to be added or modified when implementing this solution)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using multiple `setState` calls without synchronization can lead to issues, especially when one of them uses a value obtained from `

In my discovery: When there are two instances of setState The first one is invoked with a value obtained from await Both calls occur in the same thread It results in a scenario where one state is updated while the other remains unchanged. For instance: ...

Text positioned on the right side of the image, appearing to hover above

After finding a helpful example on Stack Overflow, I successfully implemented a similar layout for product boxes in a JSFiddle. I then replicated the CSS and HTML almost exactly on my Wordpress blog, but encountered an issue where the title, description, a ...

Creating dynamic groupings within a Material UI Select element based on provided data sources

I am looking to dynamically generate groupings for my Select component and want to make sure it is controlled. I have come across an issue with the ListSubheader component in Material UI. Even though the code snippet works fine without the ListSubheader c ...

Implementing relative path 'fetch' in NextJs App Router

When attempting to retrieve data using fetch("/api/status"), the URL is only detected when utilizing the absolute path: fetch("http://localhost:3000/api/status"). This is happening without storing the path in a variable. ...

The ordering of my styles and Material-UI styles is causing conflicts and overrides

Greetings fellow developers! I'm currently facing an issue with my custom styles created using makeStyles(...). The problem arises when I import my styles constant from another module, and the order of the style block is causing my styles to be overr ...

Issues with rendering in-line styles in ReactJS after a state update

I'm currently working on implementing a basic state change for a button in React. 'use strict'; class ReactButton extends React.Component { constructor(props) { super(props); this.state = {hovering: false}; } onClick() { ...

Load images in advance using jQuery to ensure they are cached and retrieve their original sizes before other activities can proceed

When a user clicks on a thumbnail, I aim to display the full-size image in a div. To achieve this, I want to determine the original size of the image based on its source URL before it loads, allowing me to set the appropriate dimensions for the container. ...

The interaction between Postgres and express.js seems to be malfunctioning when using Ubuntu environment variables

My PERN Stack is encountering an issue with the error message 'password authentication failed for user "postgres"'. In my postgres (14.8) setup on Ubuntu 22.04.2, I am able to log into postgres using either the (Ubuntu) users ubuntu or ...

Transferring Text from Word to Expression using Copy and Paste

Whenever I try to copy and paste content from a Word document into Expressions Web, I encounter some strange behavior. Often, the top line gets placed in one <span> tag while the rest ends up in another <span> tag, causing a slight gap between ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Maintain the image's aspect ratio by setting the width equal to the height when the height is

I am uncertain if achieving this purely with CSS is possible, but it would be ideal. I currently have an image: <img src="#" class="article-thumb"> CSS: .article-thumb { height: 55%; } Is there a way to set the width equal to the height? My g ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

In React Material UI, there seems to be an issue where the image and h4 elements are not displaying next

I am currently working with material ui in react. I am facing an issue where the image and h4 elements are aligned vertically instead of being placed adjacent to each other. I have tried adjusting the width, but it doesn't seem to be working. https:/ ...

Working with ReactJS, Material-UI, and Javascript: Facing challenges in applying rounded borders to TableRow components

I've been trying to achieve rounded borders on a TableRow element, but adding the style "borderRadius: 5" doesn't seem to have any effect. When I try wrapping the TableRow in a Box element with borderRadius, it does make the borders rounded but m ...

Introducing a new feature that allows automatic line breaks when using the detail

Looking to achieve centered text for a summary where the arrow, when clicked, reveals additional details. However, currently, the text and arrow are on separate lines. The goal is to have the arrow on the same line as the summary text and perfectly center ...

Experiencing issues with implementing npm package oddslib

Has anyone experienced issues with using the oddslib npm package for converting betting odds? I keep getting an error message stating "invalid odds" when trying to use this package. If you have any tips on how to properly utilize it or if you have successf ...

Having trouble with React Router 4 in a subfolder?

import { BrowserRouter as Router, Route } from 'react-router-dom' <Router> <switch> <Route exact path='/' component={main} /> <Route path='/build/signup' component={SignUp} /> </swit ...

Update the next-auth session object once the user has been successfully updated through a patch request

I've scoured the depths of the Internet in search of an answer, but alas, my efforts have been fruitless. I attempted some tricks I found online, but they didn't do the trick for me. So, once a user logs in and a session is created, how can I up ...