Alpine: [Question] AlpineJS inside of React?

Created on 26 Feb 2020  Â·  3Comments  Â·  Source: alpinejs/alpine

Alpine looks great but is it possible for me to use AlpineJS template _inside_ of React, rather than replacing React? It would be really helpful if I can use Alpine for simple toggle, etc. states and React for everything else.

Is this possible? Thanks!

Most helpful comment

It's possible but:

  • you need to register functions as window.yourFunction
  • you'll get a warnings about using : (Namespace tags are not supported by default. React's JSX doesn't support namespace tags.), @ won't be supported either

The workaround is to do something as follows, using dangerouslySetInnerHtml and an HTML string instead of JSX.

window.hello = function () {
  return {
    count: 0,
    inc() {
      this.count += 1;
    }
  }
}

const alpineWidget = `<div x-data="hello()">
  <button @click="inc()">Increment</button>
  <p x-text="count"></p>
</div>`;

const App = () => (
  <>
    <div dangerouslySetInnerHTML={{ __html: alpineWidget }}/>
  </>
);

Full write-up: https://codewithhugo.com/alpine-js-react/

All 3 comments

Try it and report back?!? 😇

It's possible but:

  • you need to register functions as window.yourFunction
  • you'll get a warnings about using : (Namespace tags are not supported by default. React's JSX doesn't support namespace tags.), @ won't be supported either

The workaround is to do something as follows, using dangerouslySetInnerHtml and an HTML string instead of JSX.

window.hello = function () {
  return {
    count: 0,
    inc() {
      this.count += 1;
    }
  }
}

const alpineWidget = `<div x-data="hello()">
  <button @click="inc()">Increment</button>
  <p x-text="count"></p>
</div>`;

const App = () => (
  <>
    <div dangerouslySetInnerHTML={{ __html: alpineWidget }}/>
  </>
);

Full write-up: https://codewithhugo.com/alpine-js-react/

Thanks!

It looks like it may not be worth it, but still interesting. I’ll keep this in mind — closing the issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

allmarkedup picture allmarkedup  Â·  4Comments

mrmathewc picture mrmathewc  Â·  4Comments

BernhardBaumrock picture BernhardBaumrock  Â·  3Comments

mikemartin picture mikemartin  Â·  3Comments

imliam picture imliam  Â·  5Comments