Search code examples
reactjsreact-springreact-animated

How to use the react spring hook with react. Basic code not working


THe animation just doesnt work with this code. What am I doing wrong?

import React from 'react'
import { useSpring, animated } from 'react-spring'


function Comp1() {
  const props = useSpring({ opacity: 1, from: { opacity: 0 } })
  return (
      <animated.div style={c1Style}>

        <h1 style={{ color: "white" }}>Component 1</h1>
        <p>It is a long established fact that a reader will be distracted
        by the readable content of a page when looking at its layout.
        The point of using Lorem Ipsum is that it has a more-or-less
        normal distribution of letters, as opposed to using 'Content here,
         content here', making it look like readable English. </p>

      </animated.div>
  )
}

const c1Style = {
  background: 'steelblue',
  color: 'white',
  padding: '1.5rem'
}

export default Comp1


Solution

  • you need to add you spring animation props to animation.div style as well:

    function Comp1() {
      const props = useSpring({ opacity: 1, from: { opacity: 0 } })
      return (
        <animated.div style={{...c1Style, ...props }}>
          <h1 style={{ color: "white" }}>Component 1</h1>
          <p>It is a long established fact that a reader will be distracted
          by the readable content of a page when looking at its layout.
          The point of using Lorem Ipsum is that it has a more-or-less
          normal distribution of letters, as opposed to using 'Content here,
           content here', making it look like readable English. </p>
        </animated.div>
      )
    }
    

    spring-animation