Pavol Hejný
Pavol Hejný

Reputation: 55

Contenteditable div doesn't focus on iPad using requestAnimationFrame

I'm working on a React app that includes contenteditable divs. I'm trying to implement a feature where clicking a button toggles the editing state of the div, and then the div is automatically focused using requestAnimationFrame. The code I have works fine on desktop and Android devices, but on iPad the focus doesn't seem to work reliably. Here's the code I'm using:

function Edit({wait}){
  const [isEditing, setEditing] = useState(false);
  return (
    <div className="box">
      <h1>{isEditing&&<>Editable </>}Content</h1>

      <div
        contentEditable={isEditing}
        ref={async (element) => {
          if (!element) {
            return;
          }

          if (!isEditing) {
            return;
          }
          
          await wait();

          element.focus();
        }}
      >
        Foo <b>bar</b>
      </div>
      <br/>
      <button
        onClick={() => {
          setEditing(!isEditing)
        }}
        className="button"
      >
        Toggle edit
      </button>
    </div>
  );
}



function App() {
  return (
    <div className="box">
      <Edit wait={()=>void(0)} />
      <Edit wait={forAnimationFrame} />
     </div>
  );
}

This works fine on desktop and Android devices, but on iPad/iPhone the focus doesn't seem to work reliably - it does not trigger the keyboard. I've tried a few different approaches, including using setTimeout instead of requestAnimationFrame, using the click event instead of touchstart, and removing the delay entirely, but nothing seems to work consistently on iPad. Can anyone suggest a solution or provide some guidance on what might be causing this issue? Thanks in advance for your help.

Upvotes: 0

Views: 93

Answers (0)

Related Questions