Getting Started
3 snippetsTSX 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 snippetsTyping 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 snippetsTyped 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.
Generic Components
2 snippetsReusable 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 snippetsConditionally 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 snippetsRendering 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 snippetsHandling 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 snippetsCSS 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>;
};