can you please guide me how to add an “interaction prop” (using loader)? wasn’t able to find it in the docs
Hi @testy_echidna! What are you trying to accomplish? Interaction props are defined in the component props that you are editing. They are used to expose event handlers to the elements using that component. See the attached screen recording for how to create an event handler prop and use it in the “Run interaction prop” action.
interesting, thanks for sharing! Actually I would want to expose a loadMore
function prop that can be triggered on button click. The code component would need to expose this prop so that a button managed by the studio can trigger it but I’m not sure if that’s possible
Maybe a way to accomplish that could to expose a boolean showMore
writable state? https://docs.plasmic.app/learn/code-components-ref/#exposing-component-state Then the button can set that state variable value.
Then you can use that state to decide whether to render more content in your component:
return (
<div>
{props.children}
{props.showMore ? <>More</> : null}
</div>
);
And if you need to run something when the user changes the showMore
state, you could use React effects…
React.useEffect(() => {
// Do stuff
}, [props.showMore]);
well that would be indeed a possible workaround! the load more function is meant to be triggered many times, it’s for an infinite loading feed. So having a function prop being exposed would be the more elegant way, but using states that would definitely possible, thanks!
Hmmm, that’s an interesting use case!
We’re currently working on allowing to register arbitrary functions as interactions. While that’s not live, another (slightly hacky) way to accomplish this could be to make the code component inject a prop in its children using React.Children / React.cloneElement API.
Suppose you have a Plasmic component named StudioComponent
and a code component named CodeComponent
. You can add a event handler prop to StudioComponent like loadMore
and then pass it from your code component to the studio component by doing something like:
function CodeComponent({ children }) {
const loadMore = () => {
// Do stuff.
};
const childrenWithProps = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { loadMore });
}
return child;
});
return (
<div>
{childrenWithProps}
</div>
);
}
Note that you would have to specify PlasmicComponent as a direct child of CodeComponent in your studio elements tree.
Oh! Actually maybe a more elegant way is to use Plasmic data context:
import { DataProvider } from "@plasmicapp/loader-nextjs";
function CodeComponent({ children }) {
const loadMore = () => {
// Do stuff.
};
return (
<DataProvider name="loadMore" data={loadMore}>
{children}
</DataProvider>
);
}
From studio you will be able to see the loadMore
function in the data picker of children of CodeComponent; or use it from studio code snippets like $ctx.loadMore
.