JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

JavaScript

import { html, render, useState } from "https://unpkg.com/htm/preact/standalone.module.js";

function randomName() {
	const names = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank"];
  return names[Math.floor(Math.random() * names.length)];
}

const AddingApples = {
	generate() {
  	const a = Math.floor(Math.random() * 10) + 1;
    const b = Math.floor(Math.random() * 10) + 1;
    
    const nameA = randomName();
    const nameB = randomName();
    
    return { a, b, nameA, nameB };
  },
  defaultAnswerValue(vars) {
    return 0;
  },
  checkAnswer(answer, { a, b }) {
  	return answer === a + b;
  },

  question({ a, b, nameA, nameB }) {
  	return html`${nameA} has ${a} apples and ${nameB} has ${b} apples. How many do they have in total?`;
  },
  answerInput({ answer, setAnswer }) {
  	return html`
    	<input
      	type="number"
        min="0"
        max="100"
        step="1"
        value=${answer}
        onChange=${event => setAnswer(Number(event.target.value))}
      />
    `;
  }
};

///////////////////////////////////////////////////////

function App({ question }) {
  const [vars] = useState(question.generate());
	const [answer, setAnswer] = useState(question.defaultAnswerValue(vars));

	function onSubmit() {
  	alert(question.checkAnswer(answer, vars));
  }

	return html`
  	<div class="question">${question.question(vars)}</div>
    <div class="answer"><${question.answerInput} answer=${answer} setAnswer=${setAnswer} /></div>
    <button onClick=${onSubmit}>Submit</button>
  `;
}

render(html`<${App} question=${AddingApples} />`, document.body);