Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting value change ReactJS

I am using ReactJS, and I was wondering whether it is possible to highlight an element in the DOM when its value has been changed.

I have a list of elements whose values update periodically. While I have no problem animating in the DOM new items coming in to the list or items leaving the list using React's animation library interface, I am struggling to figure out how to detect the actual value change of the existing elements in the list.

Any ideas on how to do so? Thank you!

like image 786
Anik Dang Avatar asked Dec 03 '15 20:12

Anik Dang


2 Answers

I had the same problem, then I decided to create a generic small module to handle it everywhere, that you can install from here

https://www.npmjs.com/package/react-change-highlight

using

yarn add react-change-highlight

what you can do to use it is to wrap you part that you want to highlight inside the component itself as follow

import ChangeHighlight from 'react-change-highlight';

export default () => {
  const [count, setCount] = useState(0);

  return (
    <ChangeHighlight>
      <div ref={React.createRef()}>{count}</div>
    </ChangeHighlight>
  );
}

and you will find the highlight on change as in the example below

I hope you find this useful

like image 50
medhatdawoud Avatar answered Nov 11 '22 09:11

medhatdawoud


If your new values are coming down as new props, then you can use the componentWillReceiveProps lifecycle method on the component. It is called just before the component is updated.

Within that method, you can compare the new values (passed as the argument to the method) and the old values (available as this.props).


For instance:

componentWillReceiveProps: function(newProps) {
    if(this.props.query != newProps.query) {
        //handle change of query prop
        //may include calls to this.setState()
    }
}
like image 40
Laizer Avatar answered Nov 11 '22 10:11

Laizer