Reputation: 391
In the project's repo the react-redux app is set with CSS in JS files. Now I'm supposed to animate pictures with mouse hover just like this website : https://www.madwell.com/
The component was initially a functional component and I have changed that to a class based component as follows:
```
class BannerContainer extends React.Component{
constructor(props){
super(props);
this.state = {
x: 0,
y: 0
};
this.handleMouseMove = this.handleMouseMove.bind(this);
}
componentDidMount(){
window.addEventListener("mousemove", this.handleMouseMove);
}
componentWillUnmount(){
window.removeEventListener('mousemove', this.handleMouseMove);
}
handleMouseMove({ x, y }){
this.setState({
x : x / window.innerWidth,
y : y / window.innerHeight
})
}
render(){
const { banner = {} } = this.props;
const {
title = ' <br> ',
text = ' <br> ',
image__google_350x80 = '',
image__app_350x80 = '',
image__bg1_1166x1878 = '',
image__bg2_961x1782 = '',
image__curve_730x151 = ''
} = banner;
return (
<Container>
<BGPatch>
{console.log(this.state.x , this.state.y)}
<img src={'/images/bg_purple.jpg'} alt="" />
</BGPatch>
```
In this example I am able to get listen to the mouse-move
event and and get the x & y coordinates accordingly. But now I have to use react-spring
library to implement it so how do I do that? Also the CSS should be written in separate JS file for each component where as in react-spring
example they directly modify the opacity
or trasform
in the Spring component directly as well which is what I don't want
the spring component example given on their docs
<Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
{props => <div style={props}>hello</div>}
</Spring>
Upvotes: 0
Views: 560
Reputation: 1435
Parallaxing effects are relatively easy to do if you have mouse coordinates, here's an example with a similar effect: https://twitter.com/0xca0a/status/1058505720574959616
It uses hooks, but the same thing applies to a regular spring. Though this is probably a good example even, because it doesn't re-render the component on mousemove, which is very fast. You wouldn't use rotates in your case, translates i guess, but the point is, you receive x/y and use it to interpolate your images into position.
EDIT: I've forked the example, this version uses translates: https://codesandbox.io/embed/r5x34869vq
Upvotes: 1