Handle the onPaste event in React-Code Examples

Victor Talmacinschi

Handle the onPaste event in React

JavaScript by Victor Talmacinschi June 16, 2022

import React, { useState } from 'react';

function App() {
  // keep track of what's been pasted in state
  const [pastedText, setPastedText] = useState('');

  // update state when user pastes something
  const handlePaste = e => {
    // get clipboard data
    const clipboardData = e.clipboardData || window.clipboardData;
    // get pasted data as text
    const pastedData = clipboardData.getData('text');
    // update state with pasted data
    setPastedText(pastedData);
  };

  return (
    <div>
      <h1>Handle the onPaste Event in React</h1>
      <textarea
        onPaste={handlePaste}
        placeholder="Paste something here!"
      ></textarea>
      {/* only show pasted text when there is some to display */}
      {pastedText && <p>{pastedText}</p>}
    </div>
  );
}

export default App;

0

23.398

Handle the onPaste event in React

JavaScript by Victor Talmacinschi June 16, 2022

import React, { useState } from 'react';

function App() {
  const [text, setText] = useState('');

  function handlePaste(e) {
    // Get clipboard data
    const clipboardData = e.clipboardData || window.clipboardData;
    // Get pasted data
    const pastedData = clipboardData.getData('Text');
    // Update state
    setText(pastedData);
  }

  return (
    <div>
      <h1>Handle the onPaste Event in React</h1>
      <textarea
        value={text}
        onPaste={handlePaste}
      />
    </div>
  );
}

export default App;

0

23.398

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories