javascript - How can you use a React hook conditionally in a function component - Stack Overflow

admin2025-04-30  1

I have a react function component that needs to use a framer motion hook to build up the props of an object called styles, however you can't use hooks conditionally, so I'd like to know how to use hooks conditionally?

let styles = {};
if (scaleUp) {
  styles.scale = useTransform(scrollYProgress, [0, 1], [1, 1.2]);    
}
if (scaleDown) {
  styles.scale = useTransform(scrollYProgress, [0, 1], [1.2, 1]);    
}  
if (fadeIn) {
  styles.opacity = useTransform(scrollYProgress, [0, 1], [0, 1]);
}
if (fadeOut) {
  styles.opacity = useTransform(scrollYProgress, [0, 1], [1, 0]);
}

I have a react function component that needs to use a framer motion hook to build up the props of an object called styles, however you can't use hooks conditionally, so I'd like to know how to use hooks conditionally?

let styles = {};
if (scaleUp) {
  styles.scale = useTransform(scrollYProgress, [0, 1], [1, 1.2]);    
}
if (scaleDown) {
  styles.scale = useTransform(scrollYProgress, [0, 1], [1.2, 1]);    
}  
if (fadeIn) {
  styles.opacity = useTransform(scrollYProgress, [0, 1], [0, 1]);
}
if (fadeOut) {
  styles.opacity = useTransform(scrollYProgress, [0, 1], [1, 0]);
}
Share Improve this question edited Jan 4 at 22:11 Drew Reese 205k18 gold badges247 silver badges274 bronze badges asked Jan 4 at 22:04 jonjon 1,5912 gold badges29 silver badges45 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 3

You can't conditionally call React hooks, you'll just need to unconditionally call each hook and apply the appropriate return values.

Example:

const scaleUp = useTransform(scrollYProgress, [0, 1], [1, 1.2]);
const scaleDown = useTransform(scrollYProgress, [0, 1], [1.2, 1]);
const fadeIn = useTransform(scrollYProgress, [0, 1], [0, 1]);
const fadeOut = useTransform(scrollYProgress, [0, 1], [1, 0]);

const styles = {};

if (effects.scaleUp) {
  styles.scale = scaleUp;    
}
if (effects.scaleDown) {
  styles.scale = scaleDown;    
}  
if (effects.fadeIn) {
  styles.opacity = fadeIn;
}
if (effects.fadeOut) {
  styles.opacity = fadeOut;
}
转载请注明原文地址:http://anycun.com/QandA/1746025967a91520.html