Home > Back-end >  Passing div style as a function argument Javascript/ React
Passing div style as a function argument Javascript/ React

Time:06-06

I'm building an application using React, framer-motion and react-intersection-observer. Inside animation.js I have a function which is imported inside App.js and used as a component in App.js.

I want to apply an aspect ratio to some divs using style as a parameter, but it doesn't work.

<FadeAnimation name={'project-image--image'} style={'--ratio':16/9} />



Failed to set an indexed property on 'CSSStyleDeclaration': Indexed property setter is not supported.

I have other divs with this property and they are displayed correctly

<div className='project-image--image' style={{'--ratio':1/2}}/>

Animation.js

export const container = {
  hidden: { opacity: 0, y: 5 },
  visible: { opacity: 1, y: 0 }
}

function FadeAnimation({ children, name, delay, duration, style }) {
  const controls = useAnimation();
  const [ref, inView] = useInView();

  useEffect(() => {
    if (inView) {
      controls.start("visible");
    }
  }, [controls, inView]);

  return (
    <motion.div className={`${name}`} style={{`${style}`}}
      ref={ref}
      animate={controls}
      initial="hidden"
      transition={{ duration: duration, delay: delay }}
      variants={{
        visible: { opacity: 1, y: 0 },
        hidden: { opacity: 0, y: 5 }
      }}
    >
      {children}
    </motion.div>
  );
}

CodePudding user response:

Have you tried:

<FadeAnimation name={'project-image--image'} style={{'--ratio':16/9}} />

(Adding another curly brace)

And then, in the FadeAnimationComponent using it as

<motion.div className={`${name}`} style={style} {/*...*/}/>
  • Related