Interpolation: Complex Value Transformations
You'll learn how to map React Spring's animated values to complex outputs like colors, CSS transforms, and custom calculations using interpolate().
The Core Idea
React Spring's animated values are typically numbers (like 0 to 1 or 0 to 100). But what if you need to animate a color from red to blue, or rotate an element while simultaneously scaling it? The interpolate() method transforms these numeric spring values into any output format you need.
Think of interpolate() as a translator: your spring speaks "numbers," but your CSS needs "colors," "transforms," or even custom units. Interpolation bridges that gap.
Basic Interpolation Syntax
import { useSpring, animated } from '@react-spring/web';
function ColorBox() {
const { progress } = useSpring({ progress: 0, from: { progress: 1 } });
const backgroundColor = progress.to(
[0, 1],
['#ff0000', '#0000ff']
);
return <animated.div style={{ backgroundColor }} />;
}
The first array [0, 1] defines input ranges, the second ['#ff0000', '#0000ff'] defines output values.
Complex Transforms
You can interpolate multiple properties into a single transform string:
const { x } = useSpring({ x: 0 });
const transform = x.to(
val => `translateX(${val}px) rotate(${val}deg) scale(${1 + val / 100})`
);
return <animated.div style={{ transform }} />;
Here, one spring value drives three simultaneous transform operations with custom math.
When to Use It
Interpolation shines when you need non-linear mappings, multi-property transforms, or output formats (colors, units) that differ from your spring's numeric values. It keeps your animation logic declarative while supporting arbitrarily complex calculations.
Key Takeaway: Use interpolate() (or the .to() method) to transform React Spring's numeric values into colors, complex transforms, or any custom output format your animation requires.