Home > Blockchain >  How to clone an HTML element in React?
How to clone an HTML element in React?

Time:02-03

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.

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.

CodePudding user response:

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;
  • Related