I am using selectionStart and selectionEnd in order to get the starting and ending point of a text selection.
Code: https://codesandbox.io/s/busy-gareth-mr04o
However, I am struggling to defined the type of the event on which they can be called on.
If I use any, the code works properly but I would prefer to know the right event.
I tried with these types:
Element
React.SyntheticEvent<HTMLDivElement>
<HTMLDivElement>
with no luck
export default function App() {
const [startText, setStartText] = useState<number | undefined>();
const [endText, setEndText] = useState<number | undefined>();
const handleOnSelect = (event: any) => { <--- I CANNOT FIND THE RIGHT EVENT TYPE
setStartText(event.target.selectionStart);
setEndText(event.target.selectionEnd);
};
return (
<Grid container direction="column" className="App">
You can type here below:
<TextField
value={"This is a example, select a word from this string"}
onSelect={(event) => handleOnSelect(event)}
/>
<br />
<Grid item>The selected word starts at character: {startText}</Grid>
<Grid item>The selected word ends at character: {endText}</Grid>
</Grid>
);
}
This is a tricky one because the material-ui
TextFieldcomponent involves multiple nested nodes. The argument that is passed to theonSelectfunction is adiv. However the event itself occurs on aninputinside thediv.This logs the
inputand then thediv.Using
event.currentTargetgets very specific Typescript information. We know that it is anHTMLDivElement. But thedivdoesn't have the propertiesselectionStartandselectionEndthat we want to access. Those exist on theinput.event.targetgives us a very vague type for anEventTarget. We don't know that the target is aninput.One option is to verify the element at runtime.
Since you know that the event will always occur on an
HTMLInputElement, I think it's safe to make an assertion.Note that
selectionStartandselectionEndproperties usenullinstead ofundefined. So you'll want to either change your state type to<number | null>or replacenullwithundefinedby using null coalescingevent.target.selectionStart ?? undefined.