React-spring

박찬영·2023년 10월 3일

React-Spring


react-spring의 기초는 SpringValues와 animated 컴포넌트 두 가지에 의존합니다.
animated 컴포넌트는 SpringValues를 style prop을 통해 받고 React 렌더링을 유발하지 않고
요소를 업데이트합니다.

animated

npm install @types/react-spring

//animated 불러오기
import { animated } from 'react-spring'

animated 를 불러오는 이유는 react-spring 에서는 animation을 구현할때
animated component 를 이용하기 때문입니다.

useSpring

import { useSpring, animated } from 'react-spring'

useSpring 을 사용해야 동적인 animation 을 이용 할 수가 있다.

const Test = () => {
	const springs = useSpring({
		from: {x : -100},
		to: {x : 0}
	})

	return (
		<animated.div style={springs}>
			...코드들
		</animated.div>
	)
}

이렇게 함수형 컴포넌트 안에서 사용하고 싶은 스타일을 useSpring 으로 정의해 준 뒤에
animated component 를 이용해서 style 안에 넣어주면 된다.

import { animated } from '@react-spring/web'  

// ✅ This will work because `div` is a web element 
	<animated.div />  

// ❌ This will not work because `mesh` is not a web element. 
	<animated.mesh />

위 코드에서 @react-spring/web에서 가져온 animated를 사용하여 요소를 애니메이션화 할 수 있습니다. animated.div은 웹 요소인 <div>를 애니메이션화하는 데 사용됩니다.
그러나 <animated.mesh>와 같이 다른 요소는 웹 요소가 아니므로 작동하지 않습니다.

useSpring 의 구성 객체

from

시작하는 지점을 설정합니다.

import { useSpring } from 'react-spring';

const x = useSpring({
	from: { x: 0 }, // 초기값 설정   
	to: { x: 100 }, // 최종값 설정 
});

to

끝나는 지점을 설정합니다.

import { useSpring } from 'react-spring';  
const x = useSpring({   
	from: { x: 0 },   
	to: { x: 100 }, // 최종값 설정 
});

loop

애니메이션을 반복할지 설정합니다.

import { useSpring } from 'react-spring';
const { x } = useSpring({
   from: { x: 0 },   
   to: { x: 100 },   
   loop: true, // 애니메이션을 반복 
});

delay

애니메이션의 지연 시간을 설정합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({   
	from: { x: 0 },   
	to: { x: 100 },   
	delay: 1000, // 1초 지연 후 애니메이션 시작 
});

immediate

애니메이션을 즉시 시작할 것인지 설정합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({ 
	from: { x: 0 },   
	to: { x: 100 },   
	immediate: true, // 애니메이션을 즉시 시작 
});

reset

컴포넌트 재랜더링 시 애니메이션을 초기화 할 것인지 설정합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({
	from: { x: 0 }, 
	to: { x: 100 },  
	reset: true, // 컴포넌트 재랜더링 시 애니메이션 초기화 
});

reverse

애니메이션을 역방향으로 재생할 지 설정합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({   
	from: { x: 0 },   
	to: { x: 100 },   
	reverse: true, // 애니메이션 역방향으로 재생 
});

pause

애니메이션을 중지 할지 설정합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({   
	from: { x: 0 },   
	to: { x: 100 },   
	pause: true, // 애니메이션 일시 중지 
});

cancel

애니메이션을 취소할 지 설정합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({   
	from: { x: 0 },   
	to: { x: 100 },   
	cancel: true, // 애니메이션 취소 
});

ref

애니메이션 제어
ref를 사용하여 애니메이션을 시작하거나 중지 하거나 다시 시작하는 등의 제어 작업을 수행할 수 있습니다.

애니메이션 값 접근
ref를 사용하여 해당 값의 현재 상태를 가져올 수 있습니다.

import { useSpring } from 'react-spring';  
const [springProps, springRef] = useSpring({   
	from: { x: 0 },   
	to: { x: 100 }, 
});

// 버튼 클릭 시 애니메이션 시작 
const startAnimation = () => { 
	springRef.start(); 
};

return ( 
	<div>
		<div style={springProps} /> 
		<button onClick={startAnimation}>Start Animation</button> 
	</div> 
); 

config

커스텀 애니메이션을 구성합니다.

import { useSpring } from 'react-spring';  
const { x } = useSpring({   
	from: { x: 0 },   
	to: { x: 100 },   
	config: { duration: 1000 }, // 커스텀 애니메이션 구성 
});

events

애니메이션이 작동할 때 이벤트를 설정할 수 있습니다.

import React from 'react';
import { useSpring } from 'react-spring';

function App() {
  const [springProps, springRef] = useSpring({
    from: { opacity: 0 },
    to: { opacity: 1 },
    events: {
      onRest: () => {
        console.log('애니메이션 완료');
      },
    },
  });

  // 버튼 클릭 시 애니메이션 시작
  const startAnimation = () => {
    springRef.start();
  };

  return (
    <div>
      <div style={ springProps } />
      <button onClick={startAnimation}>Start Animation</button>
    </div>
  );
}

export default App;

CSS-in-JS

React-spring 에서는 styled component 라이브러리를 이용할 수 있습니다.

import styled from 'styled-components'

const MyModal = styled(animated.div, { 
	width: '40vw', 
	height: '20vh', 
	borderRadius: '8px', 
	backgroundColor: '$white80'
})

하위 component 로 스타일 보내주기

animated는 고차 컴포넌트(Higher-Order Component, HOC)이므로
컴포넌트를 간단히 감싸서 해당 컴포넌트가 스타일 prop을 네이티브 요소로 전달하는 경우에는
간단히 애니메이션화할 수 있습니다.

다른 파일
const ExternalComponent = ({ style }) => { 
	return <div {...style } /> 
}

MyApp.js 
import { ExternalComponent } from 'external-library' 
import { animated, useSpring } from '@react-spring/web' 

const AnimatedDialog = animated(ExternalComponent) 

const App = () => { 
	const styles = useSpring({ 
		from: { opacity: 0, y: '6%', }, 
		to: { opacity: 1, y: 0, }, 
	}) 
	return <AnimatedDialog style={styles} /> 
}

이렇게 넘겨주면 자동적으로 상위 컴포넌트가 만든 animated 가 적용되고 하위 component 로 넘겨줘서
하위 컴포넌트에서 받아주기만 하면 그 해당 애니메이션이 적용되서 나타난다.

profile
오류는 도전, 코드는 예술

0개의 댓글