Practicing Typescript: Wrap HTML Elements

zenoan·2021년 12월 22일
0

typescript

목록 보기
9/11
post-custom-banner

Wrap HTML Elements

  • Create custom components by adding types
  • Use omit keyword to take type and remove the specified properties.
import { CustomButton } from './components/html/Button'

function App() {

	return (
    	<div className='App'>
        	<CustomButton variant='primary' onClick={() => 
    		console.log('Clicked')}>
        		Button Label
      		</CustomButton>
        </div>
    )
}
// Button when children has no restrictions
import React from 'react';

type ButtonProps = {
  variant: 'primary' | 'secondary'
} React.ComponentProps<'button'>

export const CustomButton = ({ variant, children, ...rest }: ButtonProps) => {
  return (
    <button className={`class-with-${variant}`} {...rest}>
      {children}
    </button>
  )
}
// Button when children has restrictions to only string
// Without the Omit keyword, it becomes and intersection with ReactNode type
// children: string & React.ReactNode
import React from 'react';

type ButtonProps = {
  variant: 'primary' | 'secondary'
  children: string
} & Omit<React.ComponentProps<'button'>, 'children'>

export const CustomButton = ({ variant, children, ...rest }: ButtonProps) => {
  return (
    <button className={`class-with-${variant}`} {...rest}>
      {children}
    </button>
  )
}
profile
프론트엔드 개발자
post-custom-banner

0개의 댓글