I'm trying to create a custom text editor in React, thus I've created a div
which has a contentEditable
attribute. Now I want to perform some action when the user selects a part of the inputted text. To do that I'm using the select
event as onSelect
attribute on my div. The problem is that, select
event runs not only when selecting the text, but also when I click on the input box, or after any input. How can I prevent it, so that it gets fired only when the text is selected ?
Component:
function EditorBody(props) {
return (
<div className="editor-body">
<div
className="text-section"
contentEditable
role="textbox"
placeholder="Text goes here ..."
onSelect={() => window.alert("You've selected a text")} // Runs after every input, not only when the text is selected
></div>
</div>
);
}
export default EditorBody;
CodePudding user response:
You can change the logic in your onSelect
to be able to determine whether or not to execute the selected logic.
onSelect={(event) => {
if (document.getSelection().toString().length > 0) {
// your selection logic
window.alert(document.getSelection().toString());
}
}}
This way the logic will be executed only if the user is selecting something and not on other primary events that might set off the secondary select event (focus, keypress, etc).