diff options
author | 2021-03-23 13:47:54 -0400 | |
---|---|---|
committer | 2021-03-23 13:47:54 -0400 | |
commit | 854d0feb34f605c0fe3f5627a261e327164c449e (patch) | |
tree | c7d88676affbd271fd6304a73d98c149e265f042 /src/frontend/render/react.ts | |
parent | 3f16550765cccee0de8f2f6e5451bf41aec13601 (diff) | |
download | astro-854d0feb34f605c0fe3f5627a261e327164c449e.tar.gz astro-854d0feb34f605c0fe3f5627a261e327164c449e.tar.zst astro-854d0feb34f605c0fe3f5627a261e327164c449e.zip |
Add support for React components. (#18)
* Add support for React components.
This adds support for react components via a new `extensions` config in astro.config.mjs. In the future we can extend this to do things like look at the import statements, as Snowpack does.
* Fix the tests
Diffstat (limited to 'src/frontend/render/react.ts')
-rw-r--r-- | src/frontend/render/react.ts | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/frontend/render/react.ts b/src/frontend/render/react.ts new file mode 100644 index 000000000..d55d30c00 --- /dev/null +++ b/src/frontend/render/react.ts @@ -0,0 +1,28 @@ +import React from 'react'; +import ReactDOMServer from 'react-dom/server'; + +export function __react_static(ReactComponent: any) { + return (attrs: Record<string, any>, ...children: any): string => { + let html = ReactDOMServer.renderToString( + React.createElement( + ReactComponent, + attrs, + children + ) + ); + return html; + }; +} + +export function __react_dynamic(ReactComponent: any, importUrl: string, reactUrl: string, reactDomUrl: string) { + const placeholderId = `placeholder_${String(Math.random())}`; + return (attrs: Record<string, string>, ...children: any) => { + return `<div id="${placeholderId}"></div><script type="module"> + import React from '${reactUrl}'; + import ReactDOM from '${reactDomUrl}'; + import Component from '${importUrl}'; + + ReactDOM.render(React.createElement(Component, ${JSON.stringify(attrs)}), document.getElementById('${placeholderId}')); + </script>`; + }; +} |