Posts > TS for React: Prop Types

TS for React: Prop Types

Basic Prop Type

string, number and boolean

type AppProps = {
	message: string,
	count: number,
	disabled: boolean,
}

arrays ( string[] , number[])

type AppProps = {
	names: string[], // array of string 
	ids: number[], // array of number
}

literal types

type AppProps = {
	status: 'success' | 'failed',
}

objects

type AppProps = {
	data: {
		id: number,
		first_name: string,
		last_name: string,
	}
}

arrays of object

type AppProps = {
	data: {
		id: number,
		first_name: string,
		last_name: string,
	}[]
}

functions

type AppProps = {
	// no parameter or doesn't return anything
	onClick: () => void; 
	// named function or function requiring id as number as parameter
	onChange: (id: number) => void; 
	// function need an id and explicitly returns a number
	onChange: (id: number) => number; 
	// function takes an event
	onChange: (event: React.ChangeEvent<HtmlInputElement>) => void; // 
	// or
	onClick: (event: React.MouseEvent<HtmlButtonElement>) => void;
}

optional?

type AppProps = {
	name?: string, // the ? in the end will tell TS that the type is optional 
}

setState

type AppProps = {
	setState: React.Dispatch<React.SetStateAction<number>>, //doesn't have to be number only
}

Useful React Prop Types

children

type AppProps = {
	children?: React.ReactNode,
	childrenElement: React.JSX.Element,
}

css properties

type AppProps = {
	style?: React.CSSProperties;
}

form

type AppProps = {
	onChange?:	React.FormEventHandler<HTMLInputElement>,
}

ComponentProps

// without ref
type ButtonProps = React.ComponentPropsWithoutRef<'button'>;

// with ref
type ButtonProps = React.ComponentPropsWithRef<'button'>;
👌ComponentProps are typically used when you want to create a component using a native html element like button, a, inputs or form

without ref

type ButtonProps = React.ComponentPropsWithoutRef<'button'>

export default function Button({type, autoFocus}: ButtonProps) {
	return <button {...props}>Click</button>
}

//---

import Button from '@/component/Button';

export default App(){
	return {
		<Button type='solid' autoFocus={true} />
	}
}

with ref

type ButtonProps = React.ComponentPropsWithRef<'button'>

export default function Button({type, autoFocus, ref}: ButtonProps) {
	return <button type={type} ref={ref} autoFocus={autoFocus}>Click</button>
}

// ---

import Button from '@/component/Button';

export default App(){
	return {
		<Button type='solid' autoFocus={true} ref={} />
	}
}
👌Can also use ComponentProps to get the props of a component ( reference https://www.totaltypescript.com/react-component-props-type-helper
const SubmitButton = (props: {onClick: () => void}}) => {
	return <button onClick={props.onClick}>Submit</button>
}

//---

type SubmitButtonProps = ComponentProps< typeof SubmitButton >;