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

useState replaces the current element

I have 2 buttons. Add1 and Add2

The Add2 button in the Test does not work. What am I doing wrong. I’m not very familiar with React.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";

function App() {
  const [component, setComponent] = useState([]);

  useEffect(() => {});

  const Test = observer(() => {
    return (
      <div>
        <p>
          Test -
          <button onClick={() => setComponent([...component, Test])}>
            Add 2
          </button>
        </p>
      </div>
    );
  });

  return (
    <div>
      {component.map((Input, index) => (
        <Input key={index} />
      ))}
      <button onClick={() => setComponent([...component, Test])}>Add 1</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codesandbox: https://codesandbox.io/s/react-hooks-useeffect-forked-ml77pz

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

>Solution :

You should not create component inside another component if you do not keep its reference!

Move it outside of App and add prop setComponent

const Test = observer(({setComponent}) => {
  return (
    <div>
      <p>
        Test -
        <button onClick={() => setComponent(component => [...component, Test])}>
          Add 2
        </button>
      </p>
    </div>
  );
});

function App() {
   ...
}

Then when you render, pass ‘setComponent’ to it:

<Input key={index} setComponent={setComponent} />
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