Creating this page. I have an element I want to rotate on scroll. Would prefer to use react syntax to create this 'animation'.
LeftGear = () => {
const rotate = window.scrollY / 10 % Math.PI
const divStyle = {
backgroundColor: 'purple',
transform: `scroll(${rotate})`,
}
return <img
className={this.changeClassName('circleImage')}
src="../../assets/icons/red-gear.svg"
alt="Circles Icon"
style={divStyle}
/>
}
render(){
return <LeftGear/>
}
this works to give the image a background but does not work for that scroll. So Im wondering what I'm doing wrong ?
Rotations work with transform: rotate({n}deg)
where {n}
is your radius number. For the rest, bind and event listener to the window in an useEffect hook. Instead of updating the divStyle
object, just create a reference to the image and update the style.transform
property.
React has no smart way of dealing with this, so sometimes you just have to use some vanilla JS.
import React, { useEffect, useRef } from 'react';
const LeftGear = () => {
const imageRef = useRef();
const divStyle = {
backgroundColor: 'purple',
}
useEffect(() => {
window.addEventListener('scroll', event => {
requestAnimationFrame(() => {
const rotation = window.scrollY / 10 % Math.PI;
imageRef.current.style.transform = `rotate(${rotation}deg)`;
});
});
}, []);
return (
<img
ref={imageRef}
className={this.changeClassName('circleImage')}
src="../../assets/icons/red-gear.svg"
alt="Circles Icon"
style={divStyle}
/>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.