0

I need to clone the component and insert it to the current components. I was able to do this, but when I clone the component, the values in the previous component are cleared. I need the values in the previous component to be preserved, and the values in the new cloned component to be empty. How can I do that?

import FirstBlocks from './FirstBlocks';
import SecondBlock from './SecondBlock';
import { useState } from 'react';

const formBlocks = [
  {
    Component: FirstBlock,
    props: {
      title: 'first block',
    },
    id: 1,
  },
  {
    Component: SecondBlock,
    props: {
      title: 'second block',
    },
    id: 2,
  },
];

const Form = () => {
  const [formItems, setFormItems] = useState(formBlocks);

  return (
    <>
      {formItems.map(({ Component, props, id }, index) => {
        const cloneBlock = () =>
          setFormItems((formItems) => {
            const newFormItems = [...formItems];
            newFormItems.splice(index + 1, 0, {
              Component,
              props,
              id: Date.now(),
            });
            return newFormItems;
          });

        return <Component {...props} key={id} cloneBlock={cloneBlock} />;
      })}
    </>
  );
};

export default Form;
Qwerty
  • 314
  • 4
  • 16
  • Quick google gives me identical question from some years ago: https://stackoverflow.com/q/53207745/104380 – vsync Oct 17 '21 at 11:32
  • You care cloning the component which creates a new instance and not source instance itself with all the internal state, that is not possible, as far as I know – vsync Oct 17 '21 at 11:34
  • 2
    `index` is not a suitable `key` for lists of items which change or are reordered - it will cause bugs. [See this thread](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js). – lawrence-witt Oct 17 '21 at 11:42
  • I need to create a new cloned component empty. That is, it's okay that I generate a new one. The problem is that the old component is clearing for some reason – Qwerty Oct 17 '21 at 11:43
  • I added id to key instead of index, but that did not fix the problem. Updated code – Qwerty Oct 17 '21 at 11:57
  • 1
    Previous bug is caused by using index as key. But since you've changed to using id, the state-resetting situation should've been gone by now. I've just setup a mini demo to verify, I cannot reproduce with your current code. – hackape Oct 17 '21 at 12:10
  • it turned out that the error was inside my components. Thanks for the help! – Qwerty Oct 17 '21 at 12:34

0 Answers0