简体   繁体   中英

how to add new line on to textarea on copy to clipboard?

This is my copy to clipboard code, I am using textarea but when i am pasting what i copied on code, everything is just on one line:

const CopyButton = ({ text }: { text: string }) => {
  const init_val = 'Copy';
  const [btn_val, set_value] = useState(init_val);
  const copyToClipboard = () => {
    const textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
    set_value('Copied!');
    setTimeout(() => {
      set_value(init_val);
    }, 1500);
  };

  return (
    <button className='copy-to-clipboard' onClick={copyToClipboard}>
      {btn_val}
    </button>
  );
};

I am thinking of solving this with regexp but don't know how and can't seem to find a solution around.

You have to use white-space: pre, since HTML removes white space. You can try the following code:

const CopyButton = ({ text }: { text: string }) => {
const init_val = 'Copy';
const [btn_val, set_value] = React.useState(init_val);
const copyToClipboard = () => {
  const textField = document.createElement('textarea');
  var newParagraph = document.createElement('p');
  var newContent = document.createTextNode("Samson's SR500 headphones offer exceptional sonic \nclarity and comfort in a durable, lightweight design \nperfect for studio and movile applications.");
  newParagraph.appendChild(newContent)
  document.body.appendChild(newParagraph);
  document.body.style ="white-space: pre";
  textField.select();
  document.execCommand('copy');
  textField.remove();
  set_value('Copied!');
  setTimeout(() => {
    set_value(init_val);
  }, 1500);
};

return (
  <div>
    <button className='copy-to-clipboard' onClick={copyToClipboard}>
        {btn_val}
    </button>
  </div>


 );
};

References:

You need to use textField.innerHTML or textField.textContent , textField.innerText will remove certain characters such as new lines.

Be careful using innerHTML because this will allow users of the copy function to insert their own HTML in your site which could cause an Cross Site Scripting (XSS) issue.

Interesting piece of code. Could you provide the HTML / CSS that you use with the code?

as you can see on my code i am using innerText, I digged in around and tried using textContent and it worked, just replace innerText to textContent on my code:

textField.textContent = text;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM