Home > Software engineering >  React: How to select all text in each div
React: How to select all text in each div

Time:07-10

When I pressed Ctrl A (Command A), it's select all text in the page. how can I select only the letters inside the selected div when I pressed Ctrl A (Command A)?

Below is my full code.

import React, { useState } from 'react';

const Test = () => {
  const [chatList, setChatList] = useState([]);
  const onSubmit = (e) => {
    e.preventDefault();
    const value = e.target[0].value;
    setChatList([...chatList, { value }]);
  };
  return (
    <div>
      <form onSubmit={onSubmit}>
        <textarea placeholder="Enter text"></textarea>
        <button type="submit">submit</button>
      </form>
      {chatList.map((chat, index) => (
        <div key={index} style={{ whiteSpace: 'pre-wrap' }}>
          {chat.value}
        </div>
      ))}
    </div>
  );
};

export default Test;

CodePudding user response:

Browsers are not able to selectively highlight using Ctrl A. Selecting all truly selects all text on the page. There may be browser plugins you can use to select different lines at once but you won't be able to reliably provide others with that experience.

While I don't know the exact use case, I'm going to assume it's to copy/paste the content.

I'd recommend grabbing the values of the different content areas you want and putting those into a textarea (you'll almost certainly want the textarea hidden with style="display:none").

Then, once the content is all in the textarea, you can copy it to the clipboard programatically.

Then instead of having users hit Ctrl A, you can provide an easy "Copy" button which is more instructive to people not familiar with the select all shortcut.

Here's a basic example showing the copy function in vanilla JS.

<textarea></textarea>

<script>

    // fetch the textarea
    var textarea = document.querySelector('textarea');

    // add content to the textarea
    textarea.value = '' // clear it
    textarea.value  = 'First Content Area' // this represents content from different parts of your site
    textarea.value  = 'Second Content Area' // this represents content from different parts of your site
    textarea.value  = 'Third Content Area' // this represents content from different parts of your site

    // copy it to the clipboard
    textarea.focus();
    textarea.select();
    document.execCommand('copy');

</script>

This is a very basic example of copying data. For more details, view this answer: How do I copy to the clipboard in JavaScript?

  • Related