Clone Element in ReactJS

716 Views Asked by At

I would like to copy an element with a specific reference, is it possible to do it?

CODESANDBOX: https://codesandbox.io/s/new?file=/src/App.js:0-463

enter image description here

import "./styles.css";
import React, { useRef } from "react"

export default function App() {

  const elementRef = useRef();

  const clone = React.cloneElement( elementRef );

  return (
    <div className="App">
      <h1>Test React.cloneElement()</h1>
      <h2>I would duplicate this div:</h2>


      <div 
      className="div-style"
      ref= { elementRef }>
        div original
      </div>

<span> copy: </span>

 {/*{ clone } */}
 
    </div>
  );
}
1

There are 1 best solutions below

0
On BEST ANSWER
import { useRef, useMemo, cloneElement } from "react";

export default function App() {
  const elementRef = useRef();

  const divElement = useMemo(() => {
    return <h2 ref={elementRef}>My element</h2>;
  }, [elementRef]);

  const clonedElement = useMemo(() => {
    return cloneElement(divElement);
  }, [divElement]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {divElement}
      {clonedElement}
    </div>
  );
}