Practicing Typescript: Advanced Props

zenoan·2021년 10월 28일
0

typescript

목록 보기
2/11

Advanced Props

// App.tsx
import { Status } from './components/Status'
import { Heading } from './components/Heading'
import { Oscar } from './components/Oscar'
import { Greet } from './components/Greet'

function App() {

	return (
    	<div className='App'>
        	<Status status='loading' />
        	<Heading>Placeholder text</Heading>
            <Oscar>
              <Heading>Actor name</Heading>
            </Oscar>
        	<Greet name='John' isLoggedIn={false} />
        </div>
    )
}

Union of string literals

// Status.tsx
type StatusProps = {
  status: 'loading' | 'success' | 'error'
}

export const Status = (props: StatusProps) => {
  let message
  if (props.status === 'loading') {
    message = 'Loading...'
  } else if (props.status === 'success') {
    message = 'Data fetched successfully!'
  } else if (props.status === 'error') {
    message = 'Error fetching data'
  }
  return <h2>Status - {message}</h2> //'Status - Loading...'
}

Children props

//Heading.tsx
type HeadingProps = {
  children: string
}

export const Heading = (props: HeadingProps) => {
  return <h2>{props.children}</h2>
}

Children as react component node

//Oscar.tsx
type OscarProps = {
  children: React.ReactNode
}

export const Oscar = (props: OscarProps) => {
  return <div>{props.children}</div>
}

Optional type

//Greet.tsx
type GreetProps = {
  name: string
  messageCount?: number // optional type (added ?:)
  isLoggedIn: boolean
}

export const Greet = (props: GreetProps) => {
  const { messageCount = 0 } = props // assign default value
  return (
    <div>
      {props.isLoggedIn ? (
        <h2>
          Hey {props.name}! You have {messageCount} unread messages
        </h2>
      ) : (
        <h2>Welcome Guest</h2>
      )}
    </div>
  )
}
profile
프론트엔드 개발자

0개의 댓글