Editable Text Component with click-outside-to-close feature using React Hooks

Kaung Myat Lwin
Sep 4, 2019 · 2 min read
Photo by Thomas Tastet on Unsplash

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.

Editable Text with <span> & <input>

Making it functional means we can’t use React’s built-in State and 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 useEffect , useState and 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.

  • useEffect is very similar to typical React’s life cycle methods such as componentDidMount.
  • useState is the same as the State you usually write in React Class constructor.
  • useRef is the same as using ref attribute inside DOM element, except in Functional Components we can’t access ref of 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 text prop from parent to child component.
  • Let it have it’s own state called text so we can freely update the text inside <input> as well as update <span>.
  • We shall have another state called inputVisible to control the click-toggle nature between <span> and <input /> .
  • Control click outside using ref of <input> by attaching mousedown event to document object 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!

JavaScript in Plain English

Learn the web's most important programming language.

Kaung Myat Lwin

Written by

A programmer. A troubled soul.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade