Implementing Undo/Redo in our post editor

In the simple post editor of our blog app, we have a textarea where we can write the contents of a blog post. We are now going to implement the useUndo Hook there, so that we can undo/redo any changes that we made to the text:

  1. First, we have to install the use-undo library via npm:
> npm install --save use-undo
  1. Then, we import the useUndo Hook from the library in src/post/CreatePost.js:
import useUndo from 'use-undo'
  1. Next, we define the Undo Hook by replacing the current useInput Hook. Remove the following line of code:
    const { value: content, bindToInput: bindContent } = useInput('')

Replace it with the useUndo Hook, as follows. We set the default state to ''. We also save the state to undoContent, and get the setContent, undo, and redo functions, as well as the canUndo and canRedo values:

    const [ undoContent, {
set: setContent,
undo,
redo,
canUndo,
canRedo
} ] = useUndo('')
  1. Now, we assign the undoContent.present state to the content variable:
    const content = undoContent.present
  1. Next, we define a new handler function in order to update the content value using the setContent function:
    function handleContent (e) {
setContent(e.target.value)
}
  1. Then, we have to replace the bindContent object with the handleContent function, as follows:
            <textarea value={content} onChange={handleContent} />
  1. Finally, we define buttons to Undo/Redo our changes, after the textarea element:
            <button type="button" onClick={undo} disabled={!canUndo}>Undo</button>
<button type="button" onClick={redo} disabled={!canRedo}>Redo</button>
It is important that <button> elements in a <form> element have a type attribute defined. If the type attribute is not defined, buttons are assumed to be type="submit", which means that they will trigger the onSubmit handler function when clicked.

Now, after entering text we can press Undo to remove one character at a time, and Redo to add the characters again. Next, we are going to implement debouncing, which means that our changes will only be added to the undo history after a certain amount of time, not after every character that we entered.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.181.81