TSX
React · Reference cheat sheet
TSX
React · Reference cheat sheet
📋 Overview
.tsx is TypeScript + JSX. Type props, events, and refs for safer components. Use react types (ReactNode, CSSProperties, form events).
🔧 Core concepts
- Props types —
type Props = \{ ... \}orinterface. - FC — prefer explicit props + return;
React.FCis optional and addschildrenquirks in older typings. - Events —
React.ChangeEvent<HTMLInputElement>,React.MouseEvent. - Refs —
useRef<HTMLDivElement>(null). - Generics —
function List<T>(\{ items \}: \{ items: T[] \}).
💡 Examples
import { useRef, useState, type FormEvent } from "react";
type FormProps = {
onSave: (name: string) => void;
};
export function NameForm({ onSave }: FormProps) {
const [name, setName] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
onSave(name);
inputRef.current?.focus();
}
return (
<form onSubmit={handleSubmit}>
<input
ref={inputRef}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Save</button>
</form>
);
}type ListProps<T> = {
items: T[];
renderItem: (item: T) => React.ReactNode;
};
export function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>;
}⚠️ Pitfalls
- Typing
childrenonly when needed — don’t force it on every component. as anyon props hides real bugs.- Ensure
"jsx": "react-jsx"(or compatible) intsconfig.
🔗 Related
- jsx.md — JSX without types
- props.md — prop shapes
- component.md — components
- import_export.md —
import type