putyourlightson / craft-sprig

A reactive Twig component framework for Craft CMS.
https://putyourlightson.com/plugins/sprig
MIT License
129 stars 9 forks source link

How to pass data from js/ts to sprig #322

Closed veronikafouk closed 1 year ago

veronikafouk commented 1 year ago

I'm trying to pass data from ts to a sprig component. I found the htmx.trigger() function and tried it. My component is refreshing, but i can't access the data i'm trying to pass. "Foo" is the variable i'm trying to change.

Heres my code ->

Include sprig component:

{% set pageSlug = craft.app.request.segment(1) ??? null %}
{% set siteLanguage = currentSite.language ??? null %}
{% set initialPage = craft.app.request.segment(2) ??? 1 %}

<div id="react-search-filter"></div>
{{ sprig('_sprig/estateSearchResults', {"pageSlug": pageSlug, "siteLanguage": siteLanguage, "initialPage": initialPage, "foo": null}, {'id': 'sprig-estate-search-results', 's-trigger': 'refresh' }) }}

Inside the sprig component:

{% set page = page ??? initialPage ??? 1 %}
{% set pageSlug = pageSlug ??? null %}
{% set siteLanguage = siteLanguage ??? null %}
{% set newUrl = (siteLanguage != "de" ? "/en" : "") ~ "/" ~ pageSlug ~ "/" ~ (page + 1) %}
{% set foo = foo ??? null %}

<pre>
    {{ dump(foo) }}
</pre>

<div class="pt-20">
    <button sprig s-push-url="{{ newUrl }}" s-val:page="{{ page + 1 }}">setPage</button>
    <button class="js-search-results-refresh">Refresh component and set foo to 42</button>
</div>

And the ts file:

const refreshSearchButton = document.querySelector('.js-search-results-refresh') as HTMLElement;
const bar = document.querySelector('#sprig-estate-search-results') as HTMLElement;

refreshSearchButton?.addEventListener('click', () => {
    htmx.trigger(bar, 'refresh', { foo: 42 });
});

For now it's just a dummy, because i'm trying to find a solution, but in the future i would like to pass the data from a react component to the sprig component.

Thank you in advance. Really love this framework <3

bencroker commented 1 year ago

There are several different approaches you could take, but since you’re working with JS I suggest you hook into the htmx:configRequest event.

const refreshSearchButton = document.querySelector('.js-search-results-refresh') as HTMLElement;
const bar = document.querySelector('#sprig-estate-search-results') as HTMLElement;

refreshSearchButton?.addEventListener('click', () => {
    bar.addEventListener('htmx:configRequest', function(event) {
        event.detail.parameters['foo'] = 42;
    });
    htmx.trigger(bar, 'refresh');
});

An alternative approach would be to use a hidden input field, as explained in https://github.com/putyourlightson/craft-sprig/issues/209#issuecomment-1080468340.

veronikafouk commented 1 year ago

Thank you!!! I decided to go with the htmx:configRequest event and it worked.

Have a nice day. :))