Giter VIP home page Giter VIP logo

generic-component's Introduction

Generic을 활용한 컴포넌트 추상화

Render Props를 공부하는데 제네릭을 이용해서 컴포넌트를 추상화할 수 있을 것 같다는 생각을 했다. 제네릭은 보통 추상화할 때 많이 사용하니까.

import React from 'react'

type Props<TItem> = {
  items: TItem[]
  renderEmpty: () => React.ReactElement
  renderItem: (item: TItem) => React.ReactElement
}

function List<TItem extends { name: string }>({ items, renderEmpty, renderItem }: Props<TItem>): React.ReactElement {
  if (items.length === 0) return renderEmpty()

  return (
    <ul>
      {items.map((item) => (
        <li key={item.name}>{renderItem(item)}</li>
      ))}
    </ul>
  )
}

export default List

물론 화살표 함수도 된다.

const List = <TItem extends { name: string }>({
  items,
  renderEmpty,
  renderItem
}: Props<TItem>): React.ReactElement => {
  if (items.length === 0) return renderEmpty()

  return (
    <ul>
      {items.map((item) => (
        <li key={item.name}>{renderItem(item)}</li>
      ))}
    </ul>
  )
}

이런 고민을 나만 한 게 아니었다.

원문 - React Components as TypeScript Generic Functions
번역글 - 리액트 컴포넌트를 타입스크립트 제네릭 함수처럼 쓰기

generic-component's People

Contributors

rldnrl avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.