Hovhannes Amirjanyan
Hovhannes Amirjanyan

Reputation: 83

I'm trying detect if content pasted in input or was introduced from keyboard in ReactJS

I almost reached my goal, only I'm not sure if everything works correctly here.

Look at the code itself you will understand what I mean:

const TodoApp = () => {
    const [value,setValue] = React.useState('');
  const [isPasted,setIsPasted] = React.useState(false);

  const onInput = (e) => {
    // browser returns valid result O_O
    console.log(isPasted);
    setValue(e.target.value);
  }

  const onPaste = (e) => {
    setIsPasted(true);
  }

  const onKeyUp = () => {
    setIsPasted(false);
  }


    return (
    <input 
      onInput={onInput}
      onPaste={onPaste}
      onKeyUp={onKeyUp}
      value={value}
    />
  )
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))

Upvotes: 0

Views: 1667

Answers (1)

Kaiido
Kaiido

Reputation: 137131

May not answer perfectly your actual question, but note that the InputEvent interface has a .inputType property which will give you exactly this information, so if you don't target older browsers, you can only listen for the input event and check this property against "insertFromPaste" constant:

const onInput = (e) => {
  const isPasted = e.nativeEvent.inputType.startsWith("insertFromPaste");
  // ...
}

const target = document.getElementById('target');
target.oninput = (evt) => {
  const isPasted = evt.inputType && evt.inputType.startsWith("insertFromPaste");
  target.classList.toggle('is-pasted', isPasted);
};
.is-pasted { background-color: green; }
<div contenteditable id="target">edit me</div>

Upvotes: 1

Related Questions