AI Generate TSX docs instantly

TSX Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

3 snippets

TSX basics with TypeScript and React

Basic Component

import React from 'react';

const HelloWorld: React.FC = () => {
  return <h1>Hello, World!</h1>;
};

export default HelloWorld;

Component with Props

interface GreetingProps {
  name: string;
  age?: number;
}

const Greeting: React.FC<GreetingProps> = ({ name, age }) => {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      {age && <p>Age: {age}</p>}
    </div>
  );
};

Export Variations

// Named export
export const Button: React.FC = () => <button>Click</button>;

// Default export
export default function App() {
  return <div>App</div>;
}

TypeScript in JSX

4 snippets

Typing JSX elements and components

Typed Props

interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: 'primary' | 'secondary';
  disabled?: boolean;
}

const Button: React.FC<ButtonProps> = ({
  label,
  onClick,
  variant = 'primary',
  disabled = false
}) => (
  <button onClick={onClick} disabled={disabled}>
    {label}
  </button>
);

Children Props

interface CardProps {
  title: string;
  children: React.ReactNode;
}

const Card: React.FC<CardProps> = ({ title, children }) => (
  <div className="card">
    <h2>{title}</h2>
    {children}
  </div>
);

Event Handlers

const Form: React.FC = () => {
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} />
    </form>
  );
};

Ref Typing

import { useRef } from 'react';

const InputComponent: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  const focusInput = () => {
    inputRef.current?.focus();
  };

  return <input ref={inputRef} />;
};

Hooks with TypeScript

4 snippets

Typed React hooks

useState

import { useState } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] = useState<number>(0);
  const [name, setName] = useState<string>('');

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
};

useEffect

import { useEffect, useState } from 'react';

interface User {
  id: number;
  name: string;
}

const UserProfile: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    fetch('/api/user')
      .then(res => res.json())
      .then(data => setUser(data));
  }, []);

  return user ? <div>{user.name}</div> : <div>Loading...</div>;
};

useReducer

import { useReducer } from 'react';

type State = { count: number };
type Action = { type: 'increment' } | { type: 'decrement' };

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
  }
};

const Counter: React.FC = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
};

useContext

import { createContext, useContext } from 'react';

interface ThemeContextType {
  theme: 'light' | 'dark';
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) throw new Error('useTheme must be used within ThemeProvider');
  return context;
};

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Generic Components

2 snippets

Reusable typed components

Generic List

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
}

function List<T>({ items, renderItem }: ListProps<T>) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

// Usage
<List<string>
  items={['a', 'b', 'c']}
  renderItem={(item) => <span>{item}</span>}
/>

Generic Select

interface SelectProps<T> {
  options: T[];
  value: T;
  onChange: (value: T) => void;
  getLabel: (option: T) => string;
}

function Select<T>({ options, value, onChange, getLabel }: SelectProps<T>) {
  return (
    <select onChange={(e) => onChange(options[e.target.selectedIndex])}>
      {options.map((option, index) => (
        <option key={index} value={getLabel(option)}>
          {getLabel(option)}
        </option>
      ))}
    </select>
  );
}

Conditional Rendering

3 snippets

Conditionally displaying content

Ternary Operator

const UserStatus: React.FC<{ isLoggedIn: boolean }> = ({ isLoggedIn }) => (
  <div>
    {isLoggedIn ? (
      <p>Welcome back!</p>
    ) : (
      <p>Please log in</p>
    )}
  </div>
);

Logical AND

const Notification: React.FC<{ message?: string }> = ({ message }) => (
  <div>
    {message && <div className="alert">{message}</div>}
  </div>
);

Early Return

const UserProfile: React.FC<{ user: User | null }> = ({ user }) => {
  if (!user) {
    return <div>No user found</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  );
};

Lists & Keys

3 snippets

Rendering lists efficiently

Basic List

interface Item {
  id: number;
  name: string;
}

const ItemList: React.FC<{ items: Item[] }> = ({ items }) => (
  <ul>
    {items.map((item) => (
      <li key={item.id}>{item.name}</li>
    ))}
  </ul>
);

List with Index

const NumberList: React.FC = () => {
  const numbers = [1, 2, 3, 4, 5];

  return (
    <ul>
      {numbers.map((num, index) => (
        <li key={index}>Item {num}</li>
      ))}
    </ul>
  );
};

Filtered List

interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

const TodoList: React.FC<{ todos: Todo[] }> = ({ todos }) => {
  const activeTodos = todos.filter(todo => !todo.completed);

  return (
    <ul>
      {activeTodos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
};

Forms

2 snippets

Handling form inputs

Controlled Input

const LoginForm: React.FC = () => {
  const [email, setEmail] = useState<string>('');
  const [password, setPassword] = useState<string>('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log({ email, password });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Login</button>
    </form>
  );
};

Multiple Inputs

interface FormData {
  username: string;
  email: string;
  age: number;
}

const SignupForm: React.FC = () => {
  const [formData, setFormData] = useState<FormData>({
    username: '',
    email: '',
    age: 0
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  return (
    <form>
      <input name="username" onChange={handleChange} />
      <input name="email" type="email" onChange={handleChange} />
      <input name="age" type="number" onChange={handleChange} />
    </form>
  );
};

Styling in TSX

3 snippets

CSS and inline styles

Inline Styles

const StyledDiv: React.FC = () => {
  const styles: React.CSSProperties = {
    backgroundColor: 'blue',
    color: 'white',
    padding: '10px',
    borderRadius: '5px'
  };

  return <div style={styles}>Styled Content</div>;
};

CSS Classes

import './Button.css';

const Button: React.FC<{ variant: string }> = ({ variant }) => (
  <button className={`btn btn-${variant}`}>
    Click Me
  </button>
);

Conditional Classes

const Alert: React.FC<{ type: 'success' | 'error' }> = ({ type }) => {
  const className = `alert ${type === 'success' ? 'alert-success' : 'alert-error'}`;

  return <div className={className}>Message</div>;
};

More Cheat Sheets

FAQ

Frequently asked questions

What is a TSX cheat sheet?

A TSX cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in TSX. It helps developers quickly look up syntax without searching through documentation.

How do I learn TSX quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important TSX concepts?

Key TSX concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my TSX code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your TSX code using AI.

Code Conversion Tools

Convert TSX to Other Languages

Easily translate your TSX code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate TSX Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week