0

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

  • There is a conflicting behaviour when setting your component, you're setting the same var component in different place but with the same value – Gregoire Ducharme Jul 28 '22 at 10:25
  • Click event callback function of `Add2` button inside the Test component has a closure over the initial value of `component` state, i.e. an empty array – Yousaf Jul 28 '22 at 10:26

2 Answers2

1

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} />
Oktay Yuzcan
  • 2,097
  • 1
  • 6
  • 15
-1

You have not defined the base case for this recursive render

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