Skip to content

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>
}

React.FC

  • type safety fro defaultProps but this maybe removed in future releases
  • includes children prop 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>
)

Optional Props

type HelloProps = {
  who: string
  message?: string
}

const Hello = ({who, message}: HelloProps) => {
  return <>Hello, {who}! {message && <>{message}</>}</>
}

Default Props

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}</>}</>
}

Object Props

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>)
}

Function Props

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>

Clone this wiki locally