Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()

useEffect(()=>{
    setElement(document.querySelector('#svg'))
},[])

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [element,setElement] = useState()

useEffect(()=>{
    let el = React.cloneElement(document.querySelector('#svg'))
    setElement(el)
},[])

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 :

Update:

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.

Example:

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

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

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

  return element;
};

export default CloneElement;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading