wix-incubator / mjml-react

React component library to generate the HTML emails on the fly
MIT License
993 stars 50 forks source link

Solution to unique key problem. #64

Closed daliusd closed 3 years ago

daliusd commented 3 years ago

We have bunch of warnings in our code that looks like this:

Warning: Each child in a list should have a unique "key" prop.

Check the top-level render call using <u>. See https://reactjs.org/link/warning-keys for more information.

It looks like those warnings are coming from mjml-react because children are passed as third argument to React.createElement. This is most probably wrong. E.g.:

const a = [1, 2];

function hello() {
  return (
    <div>
      {a.map((i) => (<span>{i}</span>))}
    </div>
  );
}

function hello2() {
  return (
    <div>
      <span>1</span>
      <span>2</span>
    </div>
  );
}

JSX is transformed differently for these two cases:

const a = [1, 2];

function hello() {
  return /*#__PURE__*/React.createElement("div", null, a.map(i => /*#__PURE__*/React.createElement("span", null, i)));
}

function hello2() {
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", null, "1"), /*#__PURE__*/React.createElement("span", null, "2"));
}

It seems, if children is passed as third argument when it is Array, then it is treated as result of Array.map and React issues warning about missing key.

This fix checks if children is Array and in case it is spreads is as arguments to React.createElement.

daliusd commented 3 years ago

Problem was in different location.