choojs / hyperx

🏷 - tagged template string virtual dom builder
BSD 2-Clause "Simplified" License
1.01k stars 48 forks source link

react: key warnings #43

Closed dereke closed 5 years ago

dereke commented 7 years ago

I seem to be getting a lot of key warnings when using hyperx with react. Here is an example that generates a key warning but shouldn't really:

const React = require('react')
const hyperx = require('hyperx')
const hx = hyperx(React.createElement)

hx`<div><a href="#">link</a></div>`

If I add a key to the anchor tag the warning goes away - but I shouldn't really need to do that.

Any solutions to this?

dereke commented 7 years ago

I've done a bit more research on this. When you have this JSX:

<div><a href="#">link</a></div>

it will output this JS:

  return React.createElement(
    "div",
    null,
    React.createElement(
      "a",
      { href: "#" },
      "link"
    )
  );

The example I gave above:

hx`<div><a href="#">link</a></div>`

Produces this JS:

  return React.createElement(
    "div",
    null,
    [
      React.createElement(
        "a",
        { href: "#" },
        "link"
      )
    ]
  );

Note the last parameter is an array rather than an element. React.createElement can take either an array of elements as the last parameter or a spread of elements. When an array is supplied it warns that you should add key properties to uniquely identify them.

Hyperx seems to create arrays rather than spreading the children which is why we get key warnings.

AlecRust commented 7 years ago

Any ideas on this? Is anyone using hyperx without all these React warnings?

s9k commented 7 years ago
function createElement(Component, props, children) {
    return React.createElement(Component, props, ...children);
}

const hx = hyperx(createElement);
goto-bus-stop commented 6 years ago

i think @s9k's solution is the best way to go. documentation patch welcome!