Using Next.js + React.
We wanted to use the BuilderComponent context in custom components rendered as children of other custom components.
// 404.jsx
<BuilderComponent
model={Builder.previewingModel || 'builder-page'}
context={{
callbackFn: () => console.log('hello'),
}}
/>
The context option for BuilderComponent is documented in the README for the @builder.io/react npm package: builder/packages/react at main · BuilderIO/builder · GitHub
We were rendering children as in the example of HeroWithChildren:
The issue with above, is that the children are not passed builderState.context, it is empty. To replicate the issue, try out this simplified custom component:
function CustomComponent(props) {
useEffect(() => props.builderState.context.callbackFn())
return (
<div>{props.children}</div>
)
}
It works great, until you nest a custom component that needs access to builderState.context. Then, the props.builderState.context.callbackFn() is undefined and throws an error in the child CustomComponent. The outer still works.
The simplified component tree would look like:
<CustomComponent> <- can access callbackFn()
<CustomComponent> <- cannot access callbackFn()
<div>hey</div>
</CustomComponent>
</CustomComponent>
The solution, is to render children using BuilderBlocks, and also pass the props.builderBlock.children prop, and not the props.children
function CustomComponent(props) {
useEffect(() => props.builderState.context.callbackFn())
return (
<div>
<BuilderBlocks
style={{
display: 'inline',
}}
child
parentElementId={builderBlock?.id}
dataPath='this.children'
blocks={builderBlock.children}
/>
</div>
)
}