HoloNet
baobab.net
Functional Component with Types
In TypeScript, Functional components that have Props, require their Props to be typed. There\s several ways of declaring their types and creating a new Type specifially for component props is one of them:
type CardProps = {
title: string,
description: string
}
export const Card = ({ title, description }: CardProps) => <div>
<h2>{ title }</h2>
<p>
{ description }
</p>
</div>
Functional Component with Types and Defaults
Some or all props can be optional by adding question mark in the prop type definition. We can also pass them a default value by doing the following:
import React from "react";
type CardProps = {
title: string,
description?: string // the description is optional
}
export const Card: Reacat.FC<CardProps> = ({ title = "Hello", description }) =>
<div>
<h2>{ title }</h2>
<p>
{ description }
</p>
</div>
Functional Component with Typed Properties
We don't have to create a new type for every Props, we can also type them in-place inside the components. Here's an example:
export const Button = ({ title, onClick } : {
title: string,
onClick: () => void
}) =>
<button onClick={onClick}>{title}</button>
Common Hooks
Let's see how some of the common hooks in React can be typed:
const [isOpen, setIsOpen] = useState<boolean>(false);
const [users, setUsers] = useState<IUser[] >([]);
Custom Hooks
In custom hooks, we have to keep in mind that we need to also define return types. Since we return one or more elements in the array, if we don't properly define each element type in order, we will get a Type Error, because TypeScript assumes all elements of the array to be of the same type, unless explicitely declared.
import { useState } from "react";
export const useToggle = (): [boolean, () => void] => {
const [toggleOn, setToggleOn] = useState<boolean>(false);
const updateToggle = () => {
setToggleOn((prevToggleOn) => !prevToggleOn);
};
return [toggleOn, updateToggle];
};