JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
<script type="module">
import "https://unpkg.com/@hotwired/[email protected]"
import { Application, Controller } from "https://unpkg.com/@hotwired/[email protected]/dist/stimulus.js"
const Stimulus = Application.start()
Stimulus.register("custom-stream", class extends Controller {
static get values() { return { action: String } }
connect() {
const { content, parentElement } = this.element
switch (this.actionValue) {
case "append": {
parentElement.append(content)
parentElement.style.color = "red";
break
}
default: console.error(`Don't know how to handle ${this.actionValue}!`)
}
}
})
Stimulus.register("example-creator", class extends Controller {
static get targets() { return ["source"] }
execute(event) {
event.preventDefault()
document.body.insertAdjacentHTML("beforeend", `
<turbo-stream action="append" target="my_list">
<template>${this.sourceTarget.value}</template>
</turbo-stream>
`)
}
})
</script>
</head>
<body>
<ul id="my_list">
<li>First Element</li>
</ul>
<form data-controller="example-creator" data-action="submit->example-creator#execute">
<label for="source">Turbo Stream HTML Source</label>
<textarea id="source" data-example-creator-target="source">
<template data-controller="custom-stream" data-custom-stream-action-value="append">
<li>Another Element</li>
</template>
</textarea>
<button>Execute</button>
</form>
</body>
</html>