React: Mirror what is typed

Your first controlled input: keep its text in state and show it back.

What to build

An input whose text is shown in capitals with a character count.

Requirements

  • A controlled input with the id text.
  • A p with the id mirror shows the text in capital letters, and a p with the id count shows N characters (1 character for exactly one).

Constraints

Use one state variable for the text.

Example

Typing "react" shows "REACT" and "5 characters".

Why it works

The input and the two lines all read the same state, and the capitals and the count are derived during render, so they always match what is in the box.

Hints

Hint 1

const [text, setText] = useState(""); value={text} onChange={(e) => setText(e.target.value)}.

Hint 2

The capitals and the count are computed from text during render.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

export default function App() {
  const [text, setText] = useState("");
  return (
    <div>
      <input id="text" value={text} onChange={(e) => setText(e.target.value)} />
      <p id="mirror">{text.toUpperCase()}</p>
      <p id="count">
        {text.length} {text.length === 1 ? "character" : "characters"}
      </p>
    </div>
  );
}

Lesson: Forms and controlled inputs →