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
- The Code Formatter
- A .tsx component, or the example counter component
Steps
Load the component
Press Try it or paste your component. The example is a counter with a props type, a
useStatehook and a small JSX tree, all on three lines.Check the props type
The
Propstype 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.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>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.
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
tscwill 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: