I was doing this and thought its easy until I got stuck.
I want to expand a div with on scroll down to 100% until the bottom of the div then at the bottom shrink back to 90% and on scroll top doing reverse
I have tried using: parallax library which wasn't helpful
here is a live sample: https://stackblitz.com/edit/react-ybdmbn?file=src/components/AdjustContainer.jsx
have tried to use the useEffect hook, like below
const [adjustWidth, setAdjustWidth] = useState()
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
const handleScroll = (e) => {
let scrollTop = window.scrollY
if (scrollTop !== 0) {
// console.log('e', e);
setAdjustWidth(
{
width: '100%',
transition: 'width 2s'
}
)
} else {
setAdjustWidth(
{
width: '90%',
transition: 'width 2s'
}
)
}
}
<div className={styles.AdjustContainer} style={adjustWidth}>
my content
</div>
Looks like instead of just checking if the user has scrolled, you need to check whether the div is in view and change the width accordingly.
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.isIntersecting ? setWidth('100%') : setWidth('90%');
});
};
return (
<div
ref={ele}
className="adjustContainer"
style={{ width, transition: 'width 2s' }}
>
{children}
</div>
);
};
export default AdjustContainer;