useMotionTemplate
Creates a motion value from a string template containing other motion values.
useMotionTemplate creates a new motion value from a string template containing other motion values.
const x = useMotionValue(100);
const transform = useMotionTemplate`translateX(${x}px)`; Whenever a motion value in the template changes, the returned motion value updates with its latest value.
Usage
Import useMotionTemplate from motion-sv:
import { useMotionTemplate } from "motion-sv"; useMotionTemplate is a "tagged template" function, so rather than calling it with parentheses, you write a template literal straight after it:
useMotionTemplate``; The template can combine text and motion values:
<script lang="ts">
import { motion, useMotionTemplate, useMotionValue } from "motion-sv";
const blur = useMotionValue(10);
const saturate = useMotionValue(50);
const filter = useMotionTemplate`blur(${blur}px) saturate(${saturate}%)`;
</script>
<motion.div style={{ filter }} /> The returned motion value's latest state is the template, with each motion value replaced by its latest state. Because it's a motion value too, you can pass it to style like any other.
Motion values from any hook work, like useSpring or useTransform:
<script lang="ts">
import { motion, useMotionTemplate, useMotionValue, useSpring } from "motion-sv";
const shadowX = useSpring(0);
const shadowY = useMotionValue(0);
const filter = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`;
</script>
<motion.div style={{ filter }} /> Here, useTransform turns the element's drag position into a shadow offset, so the shadow falls away from the center as you drag:
<script lang="ts">
import { motion, useMotionTemplate, useMotionValue, useTransform } from "motion-sv";
const x = useMotionValue(0);
const y = useMotionValue(0);
// The shadow falls away from the center, as if lit from above it
const shadowX = useTransform(x, [-100, 100], [-24, 24]);
const shadowY = useTransform(y, [-100, 100], [-24, 24]);
const filter = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 12px rgb(153 17 255 / 0.6))`;
</script>
<motion.div
style={{ x, y, filter, width: 100, height: 100, borderRadius: 20, background: "#9911ff", cursor: "grab" }}
drag
dragSnapToOrigin
/> Like other hooks, call useMotionTemplate during component setup, at the top level of the <script>.