-
Notifications
You must be signed in to change notification settings - Fork 41
Typescript: (4) Function Component Props
Mithi Sevilla edited this page Mar 30, 2021
·
1 revision
import * as React from "react"
type HelloProps = { who: string }
const Hello = ({who}: HelloProps) => (
<p>Hello, {who}! </p>
)
function Hello2({who}: HelloProps) {
return <p>Hello, {who}! </p>
}- type safety fro
defaultPropsbut this maybe removed in future releases - includes
childrenprop type so you don't have to define it explicitly, but it's arguably better to explicitly define it so that consumers know for sure that it's available - benefits are not that significant maybe
type HelloProps = { who: string }
const Hello: React.FC<HelloProps> = ({ who }) => (
<p>Hello, {who}!</p>
)type HelloProps = {
who: string
message?: string
}
const Hello = ({who, message}: HelloProps) => {
return <>Hello, {who}! {message && <>{message}</>}</>
}type HelloProps = {
who: string
message?: string
}
const Hello = ({who, message}: HelloProps) => {
return <>Hello, {who}! {message && <>{message}</>}</>
}
// defaultProps maybe depreciated in the future
Hello.defaultProps = {
message: "How are you?",
someOtherProp: "no type error"
// IMPORTANT: putting someOtherProp here will NOT error
// but if you use React.FC, it will raise a type error
// that's a plus for using React.FC
}
// Alternative:
// I think this is the better way
const Hello2 = ({who, message="How are you?"}: HelloProps) => {
return <>Hello, {who}! {message && <>{message}</>}</>
}type Address = {
line1: string
line2: string
zipcode: number
}
type Who = {
name: string
isFriend: boolean
address?: Address
}
type HelloProps = {
who: Who
message?: string
}
const Hello = ({who, message="How are you?" }: HelloProps) => {
let addressShown = null
if (who.address) {
const {line1, line2, zipcode} = who.address
addressShown = who.address && (<>
<p>{line1}</p>
<p>{line2}</p>
<p>{zipcode}</p>
</>)
}
return (<div>
<p>Hello, {who.name} {who.isFriend && "my friend"}!</p>
{message && <>{message}</>}
{addressShown}
</div>)
}type Props = {
color: "blue" | "red" | "yellow" | "green"
onClick: () => void
renderMessage?: (message: string) => React.ReactNode
children: string
}
const ColoredButton = ({color, onClick, renderMessage, children = "Click Me" }: Props) => {
const style= {backgroundColor: color}
const messageContent = renderMessage ? renderMessage(children) : children
return <button {...{style, onClick}}>{messageContent}</button>
}
const button = <ColoredButton
color="blue"
onClick={() => console.log("I am clicked")}
renderMessage = {(m) => <span>{m.toUpperCase()}</span>}
>
Sell
</ColoredButton>