TypeScript with React Guide

typescript
react
components

Functional Components

import React from 'react';
 
interface GreetingProps {
  name: string;
}
 
const Greeting: React.FC<GreetingProps> = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};
 
// Usage
<Greeting name="John" />

Class Components

import React, { Component } from 'react';
 
interface CounterProps {
  initialCount: number;
}
 
interface CounterState {
  count: number;
}
 
class Counter extends Component<CounterProps, CounterState> {
  state: CounterState = {
    count: this.props.initialCount,
  };
 
  render() {
    return <div>Count: {this.state.count}</div>;
  }
}
 
// Usage
<Counter initialCount={0} />

Hooks

import React, { useState, useEffect } from 'react';
 
const Timer: React.FC = () => {
  const [seconds, setSeconds] = useState<number>(0);
 
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
 
  return <div>Seconds: {seconds}</div>;
};

Event Handling

import React from 'react';
 
const Button: React.FC = () => {
  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    console.log('Button clicked!');
  };
 
  return <button onClick={handleClick}>Click me</button>;
};

Context

import React, { createContext, useContext } from 'react';
 
interface ThemeContextType {
  theme: string;
  toggleTheme: () => void;
}
 
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
 
const ThemeProvider: React.FC = ({ children }) => {
  const [theme, setTheme] = React.useState('light');
  const toggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light');
  };
 
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};
 
const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};
 
// Usage
const App: React.FC = () => {
  const { theme, toggleTheme } = useTheme();
  return (
    <div>
      <p>Current theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
};

Remember, TypeScript provides strong typing for your React components, props, state, and more!