Essentials: Next.js with custom React components using builder.io/react
…
Here’s the lowdown of what I’m trying to do:
I have a custom component that is an Image Gallery (thumbnails on the bottom, large image on top). What I would like to do is be able to update the builder state to set the currentIndex value when the next image is loaded. The component exposes an onSlide
event so I would have the currentIndex value available in it, but I don’t see any way to write to the Builder state.
FWIW, I attempted to use builderState.update(e)
, but that didn’t work as it appears e
in this case is supposed to be a function? I also tried the brute force method of doing builderState.state.currentIndex = currentIndex
in my code, but predictably, that failed miserably.
It would be very nice if there were some kind of API exposed in builderState to allow for mutating from custom components. That feels like a piece that is currently missing, or am I just oblivious?
Hi @chtbks-jason,
Usually, in the builder editor, I tried to state.currentIndex = currentIndex
in the custom code section which works for me. Referring:- Making interactive content in Builder.io with state and actions - Builder.io
Also, you can find help for creating state of custom components at Custom Code in the Builder Visual Editor
If you already give a shot to the above one, please share the builder content entry link and code for your custom component so I can try some tweaks!
@garima The issue here is pushing from my custom component into builder state directly from the custom component code, so unfortunately, neither of the links provided really tackle the situation I’m in.
I figured out a workaround involving updating a hidden DOM element and then having Builder watch that element and update state.currentIndex based on the value of that hidden DOM element.
What would be nice is to have the ability to mutate state directly from custom components, something like:
//inside of my custom component code
onSlide={(currentIndex) => {
builderState.mutateState({
...builderState,
igCurrentIndex: currentIndex
});
}
I recognize this is kind of a big request, but it feels like one of those tiny little things that would make such a better DX with Builder and React. (FWIW, I saw that Builder can use Angular observables, but as React only has one-way data-binding, it means that something would have to be added to the Builder API to handle this.
I thought of this in a different way. Thank you for the further details and for sharing the workaround for other users.
I like this feature request, such a request will certainly help us improve our product, and encourage you to submit this here:- https://ideas.builder.io/