Why doesn't onKeyDown and onKeyUp fire when attached to a span within a contenteditable div?

Viewed 56

here is a code snippet demonstrating the problem:

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  render() {
    return (
     <div contentEditable="true">
       <p>
         <span onKeyDown={(e)=>{
           alert("hello world!!")
          }}>Hello world</span>
       </p>
     </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

After focusing on the div and pressing some buttons, the alert is not triggered. Why?

https://codesandbox.io/embed/react-playground-forked-fymxg3?fontsize=14&hidenavigation=1&theme=dark

2 Answers

The content of contenteditable element is treated as user input, not being part of the DOM. Same as text in the <input> element.

Thus, you cannot interact with value of that element as you do with normal DOM - meaning no event handlers for you here.

I've faced the same issue.

However, we can add listener of clicks by all the children of the contenteditable parent.

Since someone who want to edit text of a child first click it, we can temporary "store" the child and then we know which child text is edited.

Related