_createRenderBlock
A wrapper around createRenderBlock
to give the posibility to define the
TContext
interface. This is currently a workaround as there is currently
no way in typescript to partially provide generics while having the rest
self-infer.
See
- https://github.com/microsoft/TypeScript/issues/10571
- https://github.com/microsoft/TypeScript/pull/26349
createRenderBlock
createRenderBlock
is a utility function for registering the to-be rendered
blocks and corresponding data adapters. Returns the renderBlock
function
which in turn does the actual rendering of the blocks provided it receives
data matching the interface of the registered block components.
- @param
blocks
- A Record of components which are rendered based on the data provided torenderBlock
. - @param
options
- An optional configuration object for the renderer. - @param
options.adapters
- A Record of functions with keys matching that of providedblocks
. Adapters are for transforming or enriching data before it is passed to the block component. An adapter function will run as long as its name matches that of a registered block component. - @param
options.defaultProps
- A Record of objects with keys matching that of providedblocks
. Default props are applied before any adapter and override block component default props. Useful for when instantiating multiplerenderBlock
functions where the blocks should behave differently. - @param
options.globals
- Globals are meant to be the place where one can register needed utils that all adapters should have access to. - @param
options.fallback
- A UI component to render for when the internal block error boundary catches an error. - @returns
renderBlock
function.
Example
const blocks = {
Hero: HeroComponent,
}
const adapters = {
Hero: async (props: HeroData['props'], context, globals): Promise<HeroProps> => {
const { locale } = context
const { LinkComponent } = globals
const data = (await fetch( `https://domain.com/${locale}/posts/1`).then((res) => {
return res.json()
})) as { title: string }
return {
...props,
LinkComponent,
title: `${props.title} - ${data.title}`,
}
}
}
const defaultProps = {
Hero: { color: 'brand1' },
}
const globals = {
LinkComponent: Link,
}
const renderBlock = createRenderBlock(blocks, {
adapters,
defaultProps,
globals,
fallback: FallbackComponent,
})
const blocksData = [{
blockType: 'Hero' as const,
props: { title: 'Hello World!' },
}]
const blocks = await Promise.all(blocksData.map(renderBlock))
BlockTypeMap
The interface that block data needs to conform to.
BlockAdapter
Type helper to set up a block adapter.