Skip to content

React TS

  • React: the library that we use to create the UI.
  • all react types are declared and implicitly imported in React:
  • Components types: React.FC = React.FunctionComponent, React.Classic for class components.
  • typing props: React.FC<Props> = React.FunctionComponent<Props>, React.Classic<Props> for class components.
  • Form Events: React.FormEvent = React.FormEvent<HTMLFormElement>.
  • Ref Types: const ref = useRef<HTMLInputElement>().
  • always pass a function to setState, as :
const [count, setCount] = useState<number>(0);
setCount((oldCount) => oldCount + 1); // this guarantee that you will always access the latest value of count.
  • when a state is managed to child components, do not pass the setState function; instead, define functions that interact with the state and pass them to the child components.
type Todo = { id: string; text: string; completed: boolean };
const [todos, setTodos] = useState<Todo[]>([]);

const addTodo = (text: string) => {
    const newTodo: Todo = { id: uuidv4(), text, completed: false };
    setTodos((prevTodos) => [...prevTodos, newTodo]);
};

const deleteTodo = (id: string) => {
    setTodos((prevTodos) => prevTodos.filter((todo) => todo.id !== id));
};

// ... pass those addTod, deleteTodo down to child components; not the `setTodos` function.
<TodoForm addTodo={addTodo} />;
{
    todos.map((todo) => <Todo deleteTodo={deleteTodo} />);
}
// Todo.tsx
// ...code
<div>
    {todo.text}
    <Trash
        onClick={props.deleteTodo.bind(null, todo.id)} // bind the deleteTodo function to the `Todo` object.
    />
</div>;
  • add styles, using component.module.css or inline-style:
// component.module.css
.todo {
    ...
}

// 1. use styles as `styles.className`:
import styles from "./styles.module.css";
<div className={styles.todo}></div>;

// 2. use styles as `className` (higher probability of css rules clashes):
import "./styles.module.css";
<div className="todo"></div>;

// 3. inline styles:
<div style={{ color: "red" }}></div>;