Skip to content

React, edit text on doubleclick

New Course Coming Soon:

Get Really Good at Git

How to edit some part of a page when double clicked, with React

I had the need to listen for a doubleclick event on an element, and make that element editable.

One way to do so is to use a toggle state variable, and when the element is doubleclicked we show a different element:

const [toggle, setToggle] = useState(true)
const [name, setName] = useState('test')

...

toggle ? (
  <p
    onDoubleClick={() => {
      setToggle(false)
    }}
  >{name}</p>
) : (
  <input
    type='text'
    value={project.status}
  />
)}

Then I added a few props to the input element. First, we assign a name state to the value prop.

Then we use the onChange() event listener to set the value of the name variable when there’s any change to the content of the input field.

Finally we use onKeyDown() to intercept the Enter or Escape key press event and go back to showing the p element:

<input
  type="text"
  value={name}
  onChange={(event) => {
    setName(name)
  }}
  onKeyDown={(event) => {
    if (event.key === 'Enter' || event.key === 'Escape') {
      setToggle(true)
      event.preventDefault()
      event.stopPropagation()
    }
  }}
/>

You can also add any side effect into that function, for example to save the value somewhere if you have to.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: