I use React-Spring and i want to change the offset of some component when the window size change. This is what i tried, but not working, and i always have to refresh the browser.
<ParallaxLayer
className="elements"
offset={window.innerWidth < 576 ? 2.9 : 1.5}
speed={1}
>
<h2 className="title-section Apropos"> A propos</h2>
<div className="main-Apropos">
<p className="para p1">
dolores et quas molestias excepturi sint occaecati cupiditate
</p>
<p className="para p2">
animi, id est laborum et dolorum fuga. Et harum quidem rerum
</p>
</div>
</ParallaxLayer>
should i use functional rendering ? or others solution
I think the problem is that when the window resize, it doesn't update the value and the offset doesn't change, what you should do is have a listener to see when the window resizes and save a state.
Here is an example using hooks
function useWindowSize() {
const [size, setSize] = useState([0, 0]);
useLayoutEffect(() => {
function updateSize() {
setSize([window.innerWidth, window.innerHeight]);
}
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
return size;
}
And then just use
const [width, height] = useWindowSize();
return (
<ParallaxLayer
className="elements"
offset={width < 576 ? 2.9 : 1.5}
speed={1}
>
...
</ ParallaxLayer>
)
You can have a different approach or do exactly what you want.
The simple approach is having two classes with diferent media query values and simply toggle the classes.
OR
You could use styled-components
and pass a prop with the offset where you have a media query.
const MyComponent = styled.div`
@media (your media query) {
offset: ${props => props.offset};
}
`;
But... I think something is missing in your question, aren't you using react-spring
? Maybe you should be more clear on what you are trying to do and what you are using.