Code Formatter · Tutorial

How to format a React TSX component

4 min readbeginnerUpdated

Components pasted from chats, issues or generated code are often squashed onto a few lines. You will format a TSX component so its props type, hook calls and JSX tree are easy to read and review.

What you need

Steps

  1. Load the component

    Press Try it or paste your component. The example is a counter with a props type, a useState hook and a small JSX tree, all on three lines.

  2. Check the props type

    The Props type fits within the line width, so it stays on one line with spaces after each colon and inside the braces. A longer type would be split with one member per line.

  3. Read the JSX

    The returned JSX is wrapped in brackets and indented by nesting, with each element on its own line. Attributes stay on one line until they no longer fit.

    return (
      <div className="counter">
        <span>
          {label}: {count}
        </span>
  4. Match your project

    Set Quotes, Semicolons and Trailing commas to your project's Prettier settings, then copy the result back into your editor.

Try it yourself

Opens the Code Formatter with this tutorial's sample loaded.

Try it now

Common mistakes

Pasting JSX into the JavaScript formatter
Plain JSX works there, but type annotations do not. Use this page for anything with types.
Expecting type errors to be reported
The formatter only checks syntax. A wrong prop type still formats; your editor or tsc will catch it.
Mixing quote styles in JSX
The Quotes option applies to JavaScript strings. JSX attributes keep double quotes, which is Prettier's standard behaviour.

Next steps

Go back to the Code Formatter, or keep going with one of these: