fre icon indicating copy to clipboard operation
fre copied to clipboard

Feature: class-based Component API

Open mindplay-dk opened this issue 5 years ago • 4 comments

Should we add support for the class-based Component API?

This could also be implemented as a separate package - and, interestingly, would work with React/Preact as well, enabling them to use hooks in render-methods too.

Here's a working prototype:

https://codesandbox.io/s/fre-component-i6sbs

For now, the prototype requires manually calling a useComponent function to wrap a Component subclass to a function using only hooks. (We might consider integrating this in the h function, where you could check if e.g. type.prototype.render is present, which it is on Component subclasses, but isn't on functional components.)

Features supported so far:

  • [x] constructor(props)
  • [x] componentDidMount()
  • [x] componentWillUnmount()
  • [x] props
  • [x] state
  • [x] render()
  • [x] forceUpdate()
  • [x] static defaultProps
  • [ ] static displayName
  • [x] setState(state, callback)
  • [ ] setState(function, callback)
  • [ ] shouldComponentUpdate(nextProps, nextState)
  • [ ] componentDidUpdate(prevProps, prevState, snapshot)
  • [ ] static getDerivedStateFromProps(props, state)
  • [ ] static getDerivedStateFromError(error)
  • [ ] componentDidCatch(error, info)
  • [ ] getSnapshotBeforeUpdate(prevProps, prevState)

mindplay-dk avatar Oct 19 '19 11:10 mindplay-dk

Now it seems that we can support it without any internal modification!

Maybe we can publish a @fre/component package?

or fre/compoent like preact/hooks?

yisar avatar Oct 19 '19 12:10 yisar

Now it seems that we can support it without any internal modification!

Well, almost - not quite.

You do have to replace your class-definitions before using them:

class Button extends Component {
  // ...
}

Button = useComponent(Button) // <-- ✨ replace class with function!

So at the moment this only works for individual components.

If you were to import an existing component that uses other components, that's not going to work, because the JSX references classes... unless we create an extended version of h with the class-check and call to useComponent built-in as explained above. Which is totally doable btw. 😁

or fre/compoent like preact/hooks?

That's what I was thinking. 🙂

Well, quite a few details left to figure out first, but we'll see.

mindplay-dk avatar Oct 19 '19 13:10 mindplay-dk

Do I need to give you the repo permission?

yisar avatar Oct 19 '19 13:10 yisar

Not now - this is just a prototype, let's wait until we have a finished implementation and tests.

mindplay-dk avatar Oct 19 '19 14:10 mindplay-dk