Search code examples
reactjsonclickclickclone

How to clone an element on click in React.js


I'm a beginner to react.js, and i'm using typescript for that.

I want to create an element that will duplicate itself on click, how would I do that? This is the current code:

import React from "react";

interface Props {
  emoji: string;
  text: string;
}

const Item = ({ emoji, text }: Props) => {
  const HandleClick = () => {};

  return (
    <>
      <div className="item" onClick={HandleClick}>
        <span className="emoji">{emoji}</span>
        <span className="text">{text}</span>
      </div>
    </>
  );
};

export default Item;

Tried to search on the internet, no success yet


Solution

  • You can use this code. When you click on the Item, then it will clone itself.

    import React, { useState } from "react";
    
    interface Props {
      emoji: string;
      text: string;
    }
    
    const Item = ({ emoji, text }: Props) => {
    
    // Stores the number of clicks and clones
      const [count, setCount] = useState(0);
    
      const handleClick = () => {
        setCount(count + 1); // Track the number of clicks and clones
      };
    
      return (
        <>
          {new Array(count + 1).fill(null).map((_, index) => (
            <div key={index} className="item" onClick={handleClick}>
              <span className="emoji">{emoji}</span>
              <span className="text">{text}</span>
            </div>
          ))}
        </>
      );
    };
    
    export default Item;