Skip to content

Instantly share code, notes, and snippets.

@MrJadaml
Last active December 7, 2021 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrJadaml/96c8cce1eb72d4e2ccd6dcbead305aed to your computer and use it in GitHub Desktop.
Save MrJadaml/96c8cce1eb72d4e2ccd6dcbead305aed to your computer and use it in GitHub Desktop.
Some basic examples of TypeScript use in a React component.
import { FC, ChangeEvent, FormEvent, ReactElement, useState, useRef } from 'react'
interface CompProps {
prop1: string // required
prop2?: number // optional
}
export const Comp: FC<CompProps> = ({ prop1, prop2 }): ReactElement => {
const [foo, setFoo] = useState<string>('')
const [bars, setBars] = useState<string[]>([])
const inputRef = useRef<HTMLInputElement>(null)
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
}
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setFoo(e.target.value)
}
return (
<div>
{bars.map((bar => <p>{bar}</p> )}
<form onSubmit={handleSubmit}>
<input ref={inputRef} value={foo} onChange={handleChange} />
<button>Save</button>
</form>
</div>
)
}
----
// React Context
interface IFooContext {
bar: string
}
const defaultState = {
bar: '',
}
export const FooContext = createContext<IFooContext>(defaultState)
export const FooProvider: FC = ({ children }): JSX.Element => {
const [bar, setBar] = useState('')
return (
<FooContext.Provider value={{ bar, setBar }}>
{children}
</FooContext.Provider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment