How to clone an HTML element in React?

I want to create a React component that clones an HTML element by its id.

I tried several ways but every time I get an error.

const [element,setElement] = useState()


return element

Error: Objects are not valid as a React child (found: [object HTMLImageElement]). If you meant to render a collection of children, use an array instead.

const [element,setElement] = useState()

    let el = React.cloneElement(document.querySelector('#svg'))

return element

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

>Solution :


Read the discussion in the comments about querySelector() before implementing this code.

To create a React component that clones an HTML element by its id, you can use React.createElement and pass it the HTML element, its tag name, and its properties as arguments.


import React, { useEffect, useState } from 'react';

const CloneElement = () => {
  const [element, setElement] = useState(null);

  useEffect(() => {
    const htmlElement = document.querySelector('#svg');
      React.createElement(htmlElement.tagName, {
        children: htmlElement.innerHTML,
  }, []);

  return element;

export default CloneElement;

Leave a Reply