React-spring: Best way to implement an infinite fade-in fade-out?

Created on 12 May 2018  路  2Comments  路  Source: pmndrs/react-spring

I want an image to fade-in and then fade-out in intervals of 1s with some easing. I'm not sure I understand what's the simplest way to achieve this using react-spring.

Most helpful comment

const Content = (props) => {

  const [running,setRunning] = useState(1); // 0 reset, 1 run
  useEffect(() => {
    if(running === 0) { setRunning(1) }
  }, [running===0])

  return (
    <div>
        <Spring
            delay={1200}
            config={SpringCfg.wobbly}
            reset={running===0}
            onRest={() => {setRunning(0) }}
            from={{ opacity: 0, letterSpacing:'0px' }} to={{ opacity: 1, letterSpacing: '27px' }}>
          {props => <div style={{...props,fontSize: '22px'}}>hello</div>}
        </Spring>
    </div>
  )
}

All 2 comments

@Tsury There are several ways to do it,

for instance i have an app that displays some kind of heartbeat:

heartbeat

I used old-school setInterval, should be ashamed of it actually but here goes:

state = { pulse: true }

componentDidMount() {
    this.togglePulse()
}

componentWillUnmount() {
    clearInterval(this.pulseIntervall)
}

togglePulse = () => {
    clearInterval(this.pulseIntervall)
    this.pulseIntervall = setInterval(() => this.setState(state => ({ pulse: !state.pulse })), 1000)
}

    ...
<Spring native from={{ scale: 0 }} to={{ scale: pulse ? MAX : MIN }} ...>

You could also wait for animations to stop via

onRest={() => this.setState(state => ({ fade: !state.fade })}

But this can look unnatural because springs take a bit to animate out, small hint, you can control a springs precision: config={{ ...config.default, restSpeedThreshold: 1, restDisplacementThreshold: 0.99 }}

Or time-based animations with keyframes: https://github.com/drcmda/react-spring#timeduration-based-implementations-and-addons-demo

I would probably prefer the last one today, keyframes didn't exist back then.

const Content = (props) => {

  const [running,setRunning] = useState(1); // 0 reset, 1 run
  useEffect(() => {
    if(running === 0) { setRunning(1) }
  }, [running===0])

  return (
    <div>
        <Spring
            delay={1200}
            config={SpringCfg.wobbly}
            reset={running===0}
            onRest={() => {setRunning(0) }}
            from={{ opacity: 0, letterSpacing:'0px' }} to={{ opacity: 1, letterSpacing: '27px' }}>
          {props => <div style={{...props,fontSize: '22px'}}>hello</div>}
        </Spring>
    </div>
  )
}
Was this page helpful?
0 / 5 - 0 ratings