React spring for animations
2 min readMay 1, 2021
Create simple animation with react-spring
Step 1 : install react-spring library
yarn add react-spring
Steps 2: create a components called Services.js and paste the code below
import React, { useEffect, useState } from 'react';
import ServiceDetail from '../ServiceDetail/ServiceDetail';
import './Services.css'
const Services = () => {
const [serviceData,setServiceData]=useState([]);
useEffect(()=>{
fetch('https://young-sierra-54115.herokuapp.com/services')
.then((res)=>res.json())
.then((data)=>{
setServiceData(data);
});
},[])
return (
<section className="services-container mt-5">
<div className='text-center'>
<h3 className='text-center mb-5' style={{fontSize:'36px', fontWeight:'600'}}>
<span style={{ color: '#171B4E' }}>Our </span>
<span style={{ color: '#7AB259' }}>Services</span>
</h3>
</div>
<div className='d-flex justify-content-center '>
<div className='w-75 row mt-2 pt-5 justify-content-center justify-content-between'>
{serviceData.map((service) => (
<ServiceDetail service={service} key={service._id}></ServiceDetail>
))}
</div>
</div>
</section>
);
};
export default Services;
Here i am using my own api for services data, you used your own api or for example you can use https://jsonplaceholder.typicode.com/ api’s.
Step 3: Style your Services component , create another file called Services.css and paste the code below
.services-card:hover {
background-color: #fff;
border: none;
box-shadow: 0px 10px 40px rgba(0, 0, 0, 0.1);
border-radius: 18px;
}
.services-container {
margin-top: 90px;
margin-bottom: 160px;
}
.services-container div > a {
color: #000;
}
.services-container div > a:hover {
text-decoration: none;
}
Steps 4: Now create another component called ServiceDetail.js and follow the code below :
import React from 'react';
import { Link } from 'react-router-dom';
import { useSpring, animated } from 'react-spring'
const calc = (x, y) => [-(y - window.innerHeight / 2) / 20, (x - window.innerWidth / 2) / 20, 1.1]
const trans = (x, y, s) => `perspective(600px) rotateX(${x}deg) rotateY(${y}deg) scale(${s})`
const ServiceDetail = ({service}) => {
const [props, set] = useSpring(() => ({ xys: [0, 0, 1], config: { mass: 5, tension: 350, friction: 40 } }))
return (
<animated.div
className="col-md-3 text-center services-card p-4 justify-content-center"
onMouseMove={({ clientX: x, clientY: y }) => set({ xys: calc(x, y) })}
onMouseLeave={() => set({ xys: [0, 0, 1] })}
style={{ transform: props.xys.interpolate(trans) }}>
<Link to={'service/' + service._id}>
{
service.image ? <img style={{ height: '50px' }} src={`data:image/png;base64,${service.image.img}`}/>
:
<img style={{ height: '50px' }} src={service.img} alt='' />
}
<h5 className='mt-3 mb-3' style={{fontSize:'25px', fontWeight:'800'}}>{service.title}</h5>
<p>{service.description}</p>
<p style={{fontSize:'20px', fontWeight:'600'}}>Price: {service.price}</p>
</Link>
</animated.div>
);
};
export default ServiceDetail;