Last active
March 21, 2021 06:52
-
-
Save peerreynders/14589f0b1208565ca6e5d4128f20fd01 to your computer and use it in GitHub Desktop.
Passing server generated data to client side code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="eng"> | |
<!-- | |
Originally: | |
https://elixirforum.com/t/passing-json-between-simple-reactjs-and-phoenix-elixir/19799/6 | |
See also: | |
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Embedding_data_in_HTML | |
--> | |
<head> | |
<meta charset="utf-8"/> | |
<title>Injecting server generated data into client side code</title> | |
<style> | |
ul { | |
list-style: none; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="app"></div> | |
<!-- Server generated JSON data --> | |
<script id="appProps" type="application/json"> | |
{ | |
"categories": ["1","2","3"] | |
} | |
</script> | |
<script type="module"> | |
import { createElement as h, render, Component } from 'https://unpkg.com/preact?module'; | |
function App({ categories }) { | |
return ( | |
h('ul', null, | |
...categories.map(category => h('li', {key: category}, category)) | |
) | |
); | |
} | |
// load data from script element | |
const data = document.getElementById('appProps'); | |
const props = JSON.parse(data.text); | |
render( | |
h(App, { ...props }), | |
document.getElementById('app') | |
); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment