Pass functions down to be called from Builder.io content with React

If you have a use case where you want to provide callable functions you can trigger from your Builder content there is a very easy solution with our React SDK. This can be very useful for having buttons created in Builder call functions in your app on click, to do things like add a product to cart, trigger a modal, etc.

To do this, first you will want to pass down the functions you want to call as context

<BuilderComponent name="my-model" context={{ addToCart: () => { ... } }} />

Then in Builder, select the layer you want to call this function, and add a new click event handler to it. To do this, first up your content and select the element you want to call addToCart on click, go to the data tab and choose + new event

Choose “edit action”

Then in the code editor enter:

context.addToCart()

And you’re done! Anything you pass down as context can be called from the context object in any custom JS code in Builder

1 Like

Hi Steve, I’ve read in the builder/react README that we can pass functions trough context and data props. But I want to understand what’s the best practice if you want to pass a function that updates the state of my react app? Is it context or data prop? I’ve noticed that passing the function in data prop and using a builder Input form component the input doesn’t work as expected. I’ve bound state.updateState(event.target.value) and the input only updates with the last typed character. It works well with context prop though. context.updateState(event.target.value)
When should we use data to pass functions?

Hey @luigiveoworld - a good rule of thumb is put your functions in context and your data in state. Better docs here are in progress but I hope that is helpful in the short term :slight_smile:

1 Like