@noaignitereact-utilscreateRenderBlock

_createRenderBlock

A wrapper around createRenderBlock to give the posibility to define the TAdditionalData type. This is currently a workaround as there is currently no way in typescript to partially provide generics while having the rest infer.

See

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 to renderBlock.
  • @param options - An optional configuration object for the renderer.
  • @param options.adapters - A Record of functions with keys matching that of provided blocks. 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 provided blocks. Default props are applied before any adapter and override block component default props. Useful for when instantiating multiple renderBlock 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'], additionalData, globals): Promise<HeroProps> => {
    const { locale } = additionalData
    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))