Last active
December 7, 2021 22:15
-
-
Save MrJadaml/96c8cce1eb72d4e2ccd6dcbead305aed to your computer and use it in GitHub Desktop.
Some basic examples of TypeScript use in a React component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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