How do I fade in a changing value in React?

236
January 24, 2018, at 10:17 PM

I am building a real-time data monitoring app using React. If a data value changes, I want to highlight it by fading in the new value. I'm having trouble getting it to work. Here's what I've tried:

import React from 'react';
export default class ObsValue extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {delta: 0};
    }
    componentWillReceiveProps(newProps) {
        const delta = this.props.obsValue - newProps.obsValue;
        this.setState(() => {return {delta};});
    }
    render() {
        const str_val = this.props.obsValue.toString();
        // If there is a difference, do a fade in to the new value.
        const cn = this.state.diff ? "fadeIn" : "";
        return (<div className={cn}>{str_val}</div>);
    }
}

This works the first time, but, unfortunately, not thereafter. Presumably the problem is that after the first time the component has been built, so the fade in is complete.

How do I get it to fade in with every changing value?

One thing I tried was to toggle a key whenever diff was non-zero. This signaled to React that this was a "different" component, so it did the fade in. But, this seems like a bit of a hack. There must be a more elegant solution.

Answer 1

In theory this should work, having fadeIn as a boolean in your state that will be set to true if the new props you send to your component is different from the previous ones. I should trigger a re-render and your fadeIn class should be shown on each render. Hope it helps.

constructor(props) {
    super(props);
    this.state = {
      fadeIn: false
    };
}
componentWillReceiveProps(newProps) {
    if (this.props.obsValue !== newProps.obsValue) {
      this.setState({
        fadeIn: true
      });
    }
}
render() {
    const str_val = this.props.obsValue.toString();
    return (<div className={this.state.fadeIn ? 'fadeIn' : ''}>{str_val}</div>);
}
READ ALSO
PHP Function str_repeat Equivalent JavaScript [on hold]

PHP Function str_repeat Equivalent JavaScript [on hold]

I'm trying to "translate" this function in PHP to JavascriptBut it's not working

270