JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
JavaScript
import { html, render, useState } from "https://unpkg.com/htm/preact/standalone.module.js"
function generate() {
const a = Math.floor(Math.random() * 10)
const b = Math.floor(Math.random() * 10)
return { a, b }
}
function check(question, answer) {
return answer === question.a - question.b
}
function Question({ question, answer, setAnswer }) {
return html`
${String(question.a)} - ${String(question.b)} = <input
type="number"
value=${answer}
onInput=${event => setAnswer(Number(event.target.value))}
/>
`
}
const defaultAnswerValue = null
///////////////////////////////////////////////////
function App() {
const [question] = useState(generate())
const [answer, setAnswer] = useState(defaultAnswerValue)
return html`
<${Question}
question=${question}
answer=${answer}
setAnswer=${setAnswer}
/>
${"\xa0"}
<button
onClick=${() => {
if (check(question, answer)) {
alert("Correct!")
} else {
alert("Wrong.")
}
}}
>
Check answer
</button>
`
}
render(html`<${App} />`, document.body)