preactjs / preact-compat

ATTENTION: The React compatibility layer for Preact has moved to the main preact repo.
http://npm.im/preact-compat
MIT License
949 stars 148 forks source link

Problem with children in external libs #462

Closed n0wak closed 6 years ago

n0wak commented 6 years ago

I've managed to convert my project to preact and it works perfectly except for one library (https://github.com/mzabriskie/react-draggable DraggableCore). It breaks on this code specifically:

render() {
    // Reuse the child provided
    // This makes it flexible to use whatever element is wanted (div, ul, etc)
    return React.cloneElement(React.Children.only(this.props.children), {
      style: styleHacks(this.props.children.props.style),

      // Note: mouseMove handler is attached to document so it will still function
      // when the user drags quickly and leaves the bounds of the element.
      onMouseDown: this.onMouseDown,
      onTouchStart: this.onTouchStart,
      onMouseUp: this.onMouseUp,
      onTouchEnd: this.onTouchEnd
    });
  }

I see a couple issues posted here in relation to children in preact and preact-compat and this seems to be related to that. React.Children.only throws an error even though there are children. I tried to work around it by removing the only and using this.props.children[0] as a stopgap for now (since in my case it's always one child) but it renders as <undefined />

What is the expected work around in preact for this?

developit commented 6 years ago

Hmm - any idea what the value of this.props.children looks like in the case where this breaks? Only thing I can think of would be if children is an iterable.

newtriks commented 6 years ago

@developit I've hit the same issue with the react-stripe-elements library that uses React.Children.only in two locations. Specifically at the point I added StripeProvider. I've tried various things but to no avail so far.

I've created a stripped back example project that reproduces the issue (the original project used styled-components hence the alias logic).

https://github.com/newtriks/preact-stripe-example

Here is the debug output for this.props.children:

screen shot 2018-07-31 at 11 06 30

Oops, I've just noticed this is in the preact-compat lib issues and I actually don't use it in this example. @developit if you want me to move this to a new issue in the preact lib just say and I'll do so.

Update:

After the "oops" comment above, I actually added preact-compat and 💥 it works:

https://github.com/newtriks/preact-stripe-example/commit/3b31c1abcb085c25bb569ff094f178514bbf8876

developit commented 6 years ago

I believe the OP's issue may have been related to the Uglify bug, so updating to preact@8.3.0 and preact-compat@3.18.2 should fix. I'm going to close this out since we've had no response, but please feel free to re-open if it's still happening!