Cenoc
Cenoc

Reputation: 11672

Get diff on rerender in React

Is there a way to get the diff that React is getting of the DOM/Components? I can imagine trying to store changes as they happen so the user can 'undo' the changes [and am personally interested in the availability of the diff that is underlying the rerender (perhaps it would have the components that have changed?)].

EDIT: The undo feature was just an example. I am just interested in whether the above is possible to extract from React, since it is supposedly doing a diff of new and old tree.

Upvotes: 10

Views: 1053

Answers (3)

Blair Anderson
Blair Anderson

Reputation: 20171

To answer your question: Probably, but you shouldn't do it like that

Imagine if you had the diff of the DOM, then you would have to parse the DOM and figure out which dom changes mapped to different parts of props and state.

Thats messy.

var SomeComponent = React.createClass({
  onChange: function(newData){
    currentState = _.clone(this.state.currentState)
    previousChanges = this.state.previousChanges.concat([currentState])

    this.setState({
      currentState: newData,
      previousChanges: previousChanges
    })
  },

  undo: function(){
    previousChanges = _.clone(this.state.previousChanges)
    currentState = previousChanges.pop() // removes last item and returns it

    this.setState({
      currentState: currentState,
      previousChanges: previousChanges
    })      
  },
  render: function(){
    <div>
      <SomeAwesomeThing 
        currentState={this.state.currentState} 
        onChange={this.onChange}
        onUndo={this.undo}
      />
    </div>
  }
})

You basically have to keep a pointer to the current data, and to a list of changes, where each change can easily be reverted to.

Upvotes: 0

ffxsam
ffxsam

Reputation: 27733

Use Redux in combination with redux-undo if you want undo/redo functionality.

Upvotes: 0

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

I'm trying to store changes as they happen so the user can 'undo' the changes

My proposition how to accomplish this:

React render result should be based only on states. If you give two times identical state, then DOM should be identical. Possibly child components should be stateless.

componentWillUpdate method is run after changes in props and states.

You can copy and save state after any state change.

And if user 'undo' changes then set old saved state as current state.

And DOM should be identical to previous state.

Upvotes: 7

Related Questions