Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
I had the need to listen for a double-click 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 double-clicked 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={name}
/>
)}
Then I added a few props to the input element. First, we bind the name state to the value prop.
Then we use the onChange handler 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(event.target.value)
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === 'Escape') {
setToggle(true)
event.preventDefault()
event.stopPropagation()
}
}}
/>
You can also add any side effect in that function, for example to save the value somewhere if you have to.