J
J
japan1232018-07-25 18:53:17
JavaScript
japan123, 2018-07-25 18:53:17

What is the error in the component for copying the svg icon code to the clipboard?

I expect that when you click on the button, the icon code will be copied to the clipboard. Only [object object] is
copied https://codesandbox.io/s/vv63po7zw5

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2018-07-25
@japan123

JSX is syntactic sugar over the React.createElement call. Therefore, the element described using JSX svg is just a call to React.createElement, which returns an object, which is the so-called Virtual DOM Node, according to which the library builds a node in the real DOM.
To solve your problem, you can use ref.

let iconRef;
const getIconRef = node => iconRef = node;

const IconsList = {
  internet: (
    <svg ref={getIconRef} width="22px" height="16px" viewBox="0 0 22 16" version="1.1">
      /* ... */
    </svg>
  ),
];

copyToClipboard = text => {
    var textField = document.createElement("textarea");
    textField.innerText = iconRef;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand("copy");
    textField.remove();
  };

if there are a lot of icons, then it is more rational to use renderToString from the react-dom/server package
import { renderToString } from 'react-dom/server';

textField.innerText = renderToString(/* иконка описанная JSX */);

A
Alexander Taratin, 2018-07-25
@Taraflex

You have a tree in internet jsx and not a string.
Use something like https://www.npmjs.com/package/jsx-to-string

A
Alexey P, 2018-07-25
@lynxp9

Because you are trying to add a JavaScript object to a textarea. As a result, by default, the object's toString() function is called, which returns the [object object] value you specified. To check, print to the console.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question