Skip to main content
Frontend tutorial

4.8. Value to input

Clicking +100 forty times to get 4000 is no fun, so let users type the value. An input gives us text. The action turns it into a number and ignores anything that isn't one:

export class CounterStore {
// ...
setValue = (value: string) => {
if (!isNaN(+value)) this.value = +value;
};
}

In Counter, replace the output with an input:

const { value, add, reset, setValue } = counter;

return <div className="counter">
<input aria-label="Value" value={value}
onChange={e => setValue(e.target.value)} />

Console in browser. Our store lives outside React, so we can also put it on window and play with it from the browser console. Add this at the end of /Store.ts:

declare global {
interface Window { store: Store }
}
window.store = store;
Need a hint?
  • +'abc' is NaN, so isNaN(+value) skips anything that isn't a number.
  • In the DevTools console, switch from top to the preview frame first.

Type 42, then click +1. Then open your browser's DevTools, switch the console from top to the preview frame, and run store.addCounter().

Work locally

You need Node.js 24, pnpm and Git (how to set them up). Clone this step’s starting code:

git clone --depth 1 \
--branch lesson-04-08-value-to-input-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
04-08-value-to-input
cd 04-08-value-to-input
pnpm install --frozen-lockfile
pnpm dev

To keep your own commits: git switch -c my-work.

Browse the source on GitHub (opens in a new tab)

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./04-08-value-to-input-my-files.json
pnpm dev

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…