Response, edit text on doubleclick

How to use React to edit certain parts of a page

I need to listen to the doubleclick event on the element and make the element editable.

One way is to usetoggleState variable, when double-clicking the element, we display another 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 some propsinputelement. First, we assign anameStated tovaluepillar.

Then we useonChange()Event listener to setnameWhen the content changesinputsite.

Finally we useonKeyDown()InterceptEnterorEscapeKey event and return to displaypelement:

<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 effects to the function, for example, you can save the value somewhere if necessary.

Download mine for freeResponse Handbook


More response tutorials: