0

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.

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

3 Answers3

2

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:

Shamar Yarde
  • 747
  • 1
  • 7
  • 19
0

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.

Josh Cronin
  • 550
  • 4
  • 8
-1

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;
gpbaculio
  • 5,693
  • 13
  • 60
  • 102