Editable Text Component with click-outside-to-close feature using React Hooks
Every once in awhile, this was a very common thing for UIs containing quick edits by clicking on text, edit it and then click outside to save the text.
I’ve been tasked to add this feature and I decided to make it a functional component so that I could use it on other parts of my project as well.
If you aren’t getting the picture, this is how the simple component looks like this.
Making it functional means we can’t use React’s built-in
componentDidMount as well as
ref to detect outside clicks. However with the introduction of React Hooks, this is a lot easier and cleaner!
In this case, we’ll use
useRef to leverage a Class based React component’s features.
If you aren’t familiar with any of those hooks, here is a quick run down.
useEffectis very similar to typical React’s life cycle methods such as
useStateis the same as the State you usually write in React Class constructor.
useRefis the same as using
refattribute inside DOM element, except in Functional Components we can’t access
refof DOM easily so this is a goto method whenever you want to access a DOM element.
For more details, you should read Intro to React Hooks.
Ok. So we’re armed with our knowledge about React Hooks. How do we leverage these features into our very own component.
First, we shall write the skeleton of our component’s HTML.
Second, we will think about how our component will actually work. Here is my thought flow.
- We pass
textprop from parent to child component.
- Let it have it’s own state called
textso we can freely update the text inside
<input>as well as update
- We shall have another state called
inputVisibleto control the click-toggle nature between
- Control click outside using
documentobject and see if user is clicking on our
<input>or not and toggle between two elements.
I won’t explain the very detailed aspects of full code but I included some helpful comments so you can get the gist of how I laid out the thought flow in code.
Full working Demo
Thanks for reading. I appreciate all the comments!