Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock.
What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling up. In other words, the width of the div at the top and bottom should be controlled by the scroll direction.
The project I'm working on is using SSR next.js
I attempted to use the parallax library from this link but it didn't solve my issue.
You can see a live sample here: https://stackblitz.com/edit/react-ybdmbn?file=src/components/AdjustContainer.jsx

I also tried using the useEffect hook as shown below:

const [adjustWidth, setAdjustWidth] = useState()
const adjustRef = useRef();
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [adjustRef.current]);

  const handleScroll = () => {
    console.log('scrollTop', adjustRef.current.scrollTop);
    if (adjustRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = adjustRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        // do something here
        console.log('Reached Bottom');
      }
    }
  };

      <div className={styles.AdjustContainer}  ref={adjustRef}>

            {myContent.map((module, i) => (

                    <MyContent {...module} key={i}  />
                ))}
      </div>


Answer №1

It seems that simply checking if the user has scrolled is not enough; you also need to ensure that the div is visible on the screen in order to adjust its width.

import React, { useEffect, useState, useRef } from 'react';
    
const AdjustContainer = ({ children }) => {
  const ele = useRef();
  const [width, setWidth] = useState('90%');

  useEffect(() => {
    const observer = new IntersectionObserver(handleIntersection);

    observer.observe(ele.current);

    return () => {
      observer.unobserve(ele.current);
    };
  }, []);

  const handleIntersection = (entries) => {
    entries.map((entry) => {
      entry.intersectionRatio ? setWidth('100%') : setWidth('90%');
    });
  };

  return (
    <div
      ref={ele}
      className="adjustContainer"
      style={{ width, transition: 'width 2s' }}
    >
      {children}
    </div>
  );
};
export default AdjustContainer;

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

What causes Chrome to automatically remove a script tag?

Hello everyone! Instead of utilizing jQuery, I have been creating a script tag and appending it to the head tag in order to retrieve JSONP data. However, after the JSONP callback function is executed, I have noticed that the script tag that I added to the ...

What is the best way to toggle the active class on a ul list?

After clicking, the active class remains on the original "li" instead of changing as it should. I've tried modifying the code but haven't been able to find a solution. Can someone please review what I might have missed? It seems like there's ...

What is the best way to combine a QR code and an existing image using Java script?

Looking for help in embedding a created QR code into an existing image. I am proficient in nodeJS, JavaScript, and jQuery. Any assistance would be greatly appreciated. ...

Adjusting the React Material UI TextField behavior upon a change in value while maintaining the

I have an MUI TextField component that I would like to trigger a function when it changes, while still allowing it to function as usual (without being a controlled input). <TextField onChange={(e)=>{ doSomething(e.target.value) //perhaps call ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

Update the color scheme of text labels and the title on a 3D bar graph created with amcharts

After creating a 3D stacked bar chart, I have successfully generated the graph using the provided code. However, I am looking to customize the appearance by changing the font color of all labels and the title to a different color. While I was able to mod ...

The function User.find does not exist and it is not possible to replace the `users` model after it has

Currently, I am experimenting with using mongoose, mongoDB, next, and express in a test project. Despite referencing solutions like Cannot overwrite model once compiled Mongoose and others, I am encountering issues unique to my situation. Upon initializat ...

Leveraging grunt-develop

I have recently developed a basic NodeJS + Express application that runs smoothly when I use the command node app.js. However, my current task is to incorporate grunt-develop into my project. Here is how I configured it: grunt.initConfig({ develop: { ...

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

What are the best methods for cropping SVG images effectively?

Is it possible to crop a large SVG background that has elements rendered on top of it so that it fits the foreground elements? I am using svg.js but have not been able to find a built-in function for this. Can an SVG be cropped in this way? ...

Configuration file stored within the node_modules directory

I have developed a generic npm package that contains my business logic. However, I require access to some information stored in my google cloud storage configuration files. How can I retrieve this data when my package is located within the node_modules fol ...

I am trying to figure out how to properly utilize server-only functions within Next.js middleware

In my current project, I am utilizing Next.js 13 along with the App Router feature. While attempting to include a server-specific fetch function in middleware.js, an error message is encountered: Error: Unable to import this module from a Client Compone ...

"Error encountered while trying to retrieve data from MySQL: 'An issue occurred while attempting to query the

Encountering a mysterious error with my /events API endpoint in the production version, not locally. The API queries MySQL DB and returns JSON data to the client, but for some reason, this error keeps popping up: Verified that all environmental variables ...

Attempting to modify the key values within an object, however, it is mistakenly doubling the values instead

I'm encountering an issue when trying to update key values within an object. It seems to be adding duplicate values or combining all values together instead of assigning each name a specific language slug. I can't figure out where I'm going ...

I possess a function that can retrieve the key of an Object, but now I am faced with the task of accessing the actual Object using this value in JavaScript

This is my first time seeking advice on a technical issue. I'm currently working with the following function: export function sendRequest<T>(req: RawRequest, options) { const start = Date.now(); const reqOptions: CoreOptions = { ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Creating fresh texts by pairing the values in constants with variables

Make sure to carefully read the question before proceeding. I have attempted multiple commands in order to retrieve a single variable from the server [TSE](https://old.tsetmc.com/Loader.aspx?ParTree=15131F) which serves Stock Exchange information. The pag ...

Having trouble establishing a connection between the Action and Reducer, as an error message pops up saying: "Promise not caught. Type Error: Dispatch function not

Hey pals, I'm facing an issue with the connection between Action and Reducer while attempting to send data fetched from the API. I keep getting a dispatch, not a function error and when I try to console.log(action.type), I see @@redux/INITw.y.u.w.s.a. ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...