A nice feature in many apps is to edit a title or other text inline without leaving the context that we’re in.
Here’s what we’ll be building.
Let’s take a look at the requirements for this component.
- Must show text when in rest
- Click on text to edit the text
- Enter key to save
- Esc key to exit without saving
- Click outside to save
Cool let’s start by creating the resting state. We’re going to do some basic styling with CSS to help us.
- Must show text when in rest
This sets is us up with a simple text component that displays our text. Now the trickery begins! We want to click on the text and have the input show up. Let’s create some state to track whether we’re at rest or active.
Cool, now we have some state to help us display/hide our text and input. We also need some state to track what is being typed in our input. Let’s add another useState
to hold that text.
Let’s hook this state up to our elements.
- Click on text to edit the text
Alright, now we need to set up the saving and escaping of the text. We can do this with a useEffect
and useKeypress
hook that watch for a key click and take an action.
- Enter key to save
- Esc key to exit without saving
Next we’ll add a useRef
on the wrapping span to help us tell if a click happened outside of the component. We’re going to use the useOnClickOutside
hook from useHooks.com.
- Click outside to save
We can help the user by focusing the input when they click on the text. To do this we can add a useRef
on the input and a useEffect
that watches to see if the input is active.
That was a lot of little parts. Let’s put it together to see what we have. I’ve added a few helper functions as well.
It’s worth noting that input text may need to be sanitized before being saved. I’ve had good luck with DOMPurify.
That’s it! Go forth and edit!