hi I'm trying to create a react contenteditable div component that works like an input field but with some additional features that I want to implement, but since there are just few features, I want to implement it myself and not use something like slatejs or draftjs that do so much heavy lifting.
my idea is that I should have a controlled contenteditable div that I listen on events that insert some text. (like general idea of react controlled components)
it looked straightforward. I should listen on keydown events and on each event I just insert the corresponding character(event.key) into my state. however I found that on mobile devices with touch keyboards this value(event.key) is always 'Unidentified'.
also sometimes the input events have a 'data' property that determines the inserted value. but in touch keyboard that event doesn't have 'data' property.
so my question is how can we get inserted characters in a way that works globally on desktop and mobile? how do draftjs and slatejs authors detect inserted characters (even on touch mobile) and update their state?
I finally got the answer
it turns out that in react there is an event called onBeforeInput
that can be used on contenteditable divs and has a property called data
that corresponds to the text that is going to be inserted (on both mobile and desktop). this event is cancelable so you can call preventDefault
on it and update your state.
unfortunately this event was not mentioned in any of react docs (!!) and I found it from an issue on their github repo.