react-undoable 🔄

Easily undo/redo any state in React, no external dependencies.

Installation
$ yarn add react-undoable
TypeScript
This library utilizes TypeScript and exposes a full set of
TypeScript definitions.
Usage
This library exposes a default Undoable
component that is used to manage the state you wish to undo/redo. This component wraps any number of child components and provides a simple API to manage the state.
Example
import React, { PureComponent } from 'react'
import Undoable, { IUndoable } from 'react-undoable'
import ReactDOM from 'react-dom'
interface IMyComponentProps extends IUndoable<IMyComponentState> {}
interface IMyComponentState {
count: number
random: number
}
const initialState IMyComponentState = {
count: 0,
random: 42,
}
class MyComponent extends PureComponent<IMyComponentProps> {
up = () => {
const { currentState, pushState } = this.props
return pushState({
...currentState,
count: currentState.count + 1,
})
}
down = () => {
const { currentState, pushState } = this.props
return pushState({
...currentState,
count: currentState.count - 1,
})
}
random = () => {
const { currentState, updateState } = this.props
return updateState({
...currentState,
count: currentState.count - 1,
})
}
render() {
const { currentState, undo, redo, resetState } = this.props
return (
<div>
<h1>Count: {currentState.count}</h1>
<h4>Random {currentState.random}</h4>
<div>
<a onClick={this.up}>Up</a>
{` | `}
<a onClick={this.down}>Down</a>
{` | `}
<a onClick={this.random}>Random</a>
</div>
<div>
<a onClick={undo}>Undo</a>
{` | `}
<a onClick={redo}>Redo</a>
{` | `}
<a onClick={resetState}>Reset</a>
</div>
</div>
)
}
}
const App = () => (
<Undoable initialState={initialState}
{undoable => (
<MyComponent {...undoable} />
)}
</Undoable>
)
ReactDOM.render(App, '#app')
API
react-undoable exposes a small API to use in your child components.
<Undoable />
Initializes the main Undoable component that manages state. Renders a child function that passed
the different state trees and methods to manage state.
Props
interface IUndoableProps<T> {
initialState: T
children(props: IUndoableState<T> & IUndoableMethods<T>): React.ReactNode
}
Methods
The Undoable component passes down the following methods in the child function.
pushState(state: T): void
Pushes a new state to the stack. This tracks the change so it can be undone or redone.
updateState(state: T): void
Update the state but do not track the change. This is useful for when you want to update the
state but do not want undo/redo to apply the previous change (e.g. highlighting a selected layer)
undo(): void
Undo the current state and replace with the previously tracked state.
redo(): void
Redo a previous undone state.
resetState(): void
Reset the state stack so there are no undos/redos.
License
MIT