preactjs / preact-compat

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

preact-compat Children.only differs from Reacts Children.only #506

Closed Hotell closed 4 years ago

Hotell commented 5 years ago

React's Children.only uses isValidElement under the hood. I guess we should same errors like within react.

Use case:

you component should be restricted to have one children and it should be a function ( render prop pattern via children )

This is valid within preact+preact-compat

class Test extends Component {
  render() {
    const children = Children.only(this.props.children);

    if (typeof children !== 'function') {
      throw new Error('we need 1 function human!');
    }

    return children();
  }
}

in react it will on Children.only(this.props.children) when child's gonna be a function, because of mentioned isValidElement:

https://github.com/facebook/react/blob/master/packages/react/src/ReactChildren.js#L389

class Test extends Component {
  render() {
    // error
    const children = Children.only(this.props.children);

    if (typeof children !== 'function') {
      throw new Error('we need 1 function human!');
    }

    return children();
  }
}
const App = () => <Test>{() => <div>just testing</div>}</Test>;
marvinhagemeister commented 4 years ago

This is resolved in Preact X. Make sure to alias preact/compat instead of preact-compat.