Yield for render props
Use generator functions to harness the power of “render props” while avoiding “callback hell”.
Why call it “yender”? It’s a portmanteau of “yield” and “render”
Note: This is essentially a mirror of epitath with Typescript support (and a better name, imo).
import {yender} from 'yender'
const HelloWorld = yender(function* () {
const {foo} = yield <Foo ></Foo>
console.log(foo) // => true
return 'Hello world'
})
const element: JSX.Element = <HelloWorld ></HelloWorld>
Where Foo
is the following:
import {Render} from 'yender'
const Foo = (props: FooProps) =>
props.children({ foo: true })
interface FooProps {
// Children must be optional.
children?: Render<{ foo: true }>
}
In the HelloWorld
generator function, the foo
variable returned by yield <Foo ></Foo>
is untyped (see here).
For type safety, we need to use explicit types:
import {RenderProps as P} from 'yender'
const HelloWorld = yender(function* () {
// `typeof` is required because `Foo` is a function, not a class
const {foo}: P<typeof Foo> = yield <Foo ></Foo>
const bar: string = foo // [ts] Type 'true' is not assignable to type 'string'.
console.log(foo) // => true
return 'Hello world'
})
@yender
decoratorComponent classes are supported, too!
import {Component} from 'react'
import {yender} from 'yender'
@yender
class HelloWorld extends Component {
*render() {
const {foo} = yield <Foo ></Foo>
return 'Hello ' + this.props.world
}
}
// Without decorators
yender(HelloWorld)