iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌊

Type definitions for components with children using normal functions

に公開

In this article, I will explain how to define types when writing a component with children using a function.

How to Write

You can do this by using React.PropsWithChildren<Props>.

Sample PropsWithChildren - CodeSandbox

type Props = {}
function Component(props: React.PropsWithChildren<Props>) {}

Different Ways of Writing

/* Without children */
// arrow function
const DecorateConst = (props: Props) => {
  return <span>{props.name}</span>
}

// normal function
function DecorateFunc(props: Props) {
  return <span>{props.name}</span>
}

/* With children */
// arrow function
const DecorateConstHasChild: React.FC<Props> = (props) => {
  return <div>{props.children}</div>
}

// normal function
function DecorateFuncHasChild(props: React.PropsWithChildren<Props>) {
  return <div>{props.children}</div>
}

If you type a component with React.FC even though the Props do not have children,
you won't notice even if you write it in an unexpected way.

const Badge: React.FC<{}> = () => {
  return <span>Yo</span>
}

const Component = () => {
  // no Error
  return <Badge>hoge</Badge>
}

You can use several shorthands as follows.

const Component = (props: Props) => {
  return <span>{props.name}</span>
}

// ↓

const Component = ({ name }: Props) => {
  return <span>{name}</span>
}

// ↓

const Component = ({ name }: Props) => <span>{name}</span>
GitHubで編集を提案

Discussion