1

ChildComponent displays different fragments depending on the index passed in. This works fine, but if I have input element on multiple fragments and I put a value in one it gets automatically copied to the others. Why is this happening and how can I stop it?

const { Fragment } = React;

const fragments = (onChangeHandler) =>
  [
    <input type="text" id="screen1_input1" onChange={onChangeHandler} />,
    <input type="text" id="screen2_input1" onChange={onChangeHandler} />
  ];

const ChildComponent = ({ index, fragments }) => {
    const onChange = e => {
    const { target: {id, value} } = e;
    console.log(id, value);

        const newData = {
            ...contentData,
            [e.target.id]: e.target.value
        }
        setContentData(newData)
    };

  return (
    <Fragment>
      <h2 className="screens">{fragments(onChange)[index]}</h2>
    </Fragment>
  );
};

const ParentComponent = props => {
  return <ChildComponent index={1} fragments={fragments}/>;
};

ReactDOM.render(<ParentComponent />, document.getElementById("react"));
S.W.
  • 117
  • 2
  • 10

1 Answers1

3

Give them unique keys like so:

const fragments = (onChangeHandler) =>
  [
    <input key="key1" type="text" placeholder="input 1" id="screen1_input1" onChange={onChangeHandler} />,
    <input key="key2" type="text" placeholder="input 2" id="screen2_input1" onChange={onChangeHandler} />
  ];

Here a Sandbox to demonstrate it: https://codesandbox.io/s/keen-sun-vsk3e?file=/src/App.js:709-710

React uses the key prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one.

Reference: https://stackoverflow.com/a/43892905/1927991

codemonkey
  • 7,325
  • 5
  • 22
  • 36