user2719094
user2719094

Reputation: 1752

How do I use percentages with MotionValues in Framer Motion?

Using Framer Motion's useTransform I want to change the width of an element using a MotionValue that is a percent (eg. 75%) rather than in pixels.

The default assumes pixels:

<motion.div className="dynamic-element" style={{ width: w }}>

I want something like the following:

<motion.div className="dynamic-element" style={{ width:`${w}%` }}>

Which obviously doesn't work.

How can I specify that my MotionValue is a percentage and not pixel-based?

Alternatively, I can use filter: scale() but that results in the contents being blurry (and yes I've looked into how to fix that, but haven't had any success).

Upvotes: 6

Views: 8961

Answers (3)

dalvacoder
dalvacoder

Reputation: 475

You can use percentages as the output value.

const width = useTransform(w, [0, someOtherNumberYouPick], ['0%', '100%'])
...
<motion.div className="dynamic-element" style={{ width }}>

Upvotes: 2

Vincent Cano
Vincent Cano

Reputation: 41

You can do it like this :

useTransform(w, (value) => `${value}%`);

Upvotes: 4

amann
amann

Reputation: 5902

Can you use variants?

E.g.:

<motion.div
  variants={{
    a: {width: '20%'},
    b: {width: '50%'}
  }}
  animate={variant}
/>

See this CodeSandbox demo.

Upvotes: 0

Related Questions