Current Size:
Chakra BreakPoints
base0px
sm480px
md768px
lg992px
xl1280px
2xl1536px
Current Height:Width
widthpx
heightpx

Subjects

Reactjs With TypeScript Index

Date Created: 2022/10/28

Last Update: 2023/06/16

#reactjs #typescript #cheatsheet #reference #notes

React TypeScript CheatSheet

React Props Cheatsheet

Ignore Type Errors

Ignore TypeScript Errors on File

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck

Ignore TypeScript Errors on Next Line

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore

Basic Props Types

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

Arrays And Object Props Tyes

Array

type AppProps = {
names: string[]
}

String Litteral Exact Values

type AppProps = {
status: "loading" | "success" | "error"
}

Objects

type AppProps = {
/** interface with no required properties **/
obj: {}
/** useful placeholder **/
obj2: object
}

Single Object Multiple Types

type AppProps = {
obj: {
lkes: number
id: string
title: string
description: string
}
}

Array of Objects

type AppProps = {
objArr: {
id: string
title: string
description: string
}[]
}

Dictionaries

type AppProps = {
dict: {
[key: string]: TypeHere
}
}

or

type AppProps = {
dict: Record<string, TypeHere>
}

Function Types

type AppProps = {
onClick: () => void
}
type AppProps = {
onClick: (id: number) => void
}

Function Type with Event

type AppProps = {
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void
/**alternative**/
onClick: (event: React.MouseEvent<HTMLInputElement>) => void
}

Other types

type AppProps = {
optional?: OptionalType
}

setState type

type AppProps = {
setState: React.Dispatch<React.SetStateAction<number>>
}

Typing React Component as Children

npm i @types/react
type FooProps = {
children: React.ReactNode
}
export const Foo = ({ children }: FooProps) => {
return <div>{children}</div>
}

Examples

Simple Example of Baisc Prop Types

//....
const App = () => {
return (
<div>
<Greet name="Ben"/>
<MessageCount count={5}>
<DarkToggle isDark={true}>
</div>
)
}

string type

type GreetProps = {
name: string
}
export const Greet = (props: GreetProps) => {
return (
<div>
<h3>Welcome to React TypeScript {props.name}</h3>
</div>
)
}

or

component/greet.tsx
type GreetProps = {
name: string
}
export const Greet = ({name}: GreetProps) => {
return (
<div>
<h3>Welcome to React TypeScript {props.name}
</div>
)
}

number Type

component/message.tsx
type MessageProps = {
count: number
}
export const Greet = ({ count }: MessageProps) => {
return (
<div>
<p>You have {count} messages</p>
</div>
)
}

boolean Type

component/DarkToggle.tsx
type DarkToggleProps = {
isDark: boolean
}
export const Greet = ({ isDark }: DarkToggleProps) => {
return (
<div>
<p>You are using dark mode {isDark ? "true" : "false"}</p>
</div>
)
}

More Notes

All Notes
HomeProjects

Links

Home Articles Notes Projects About Style Guide Site Credits

Contact

 [email protected]

Location

🌎 Earth