Skip to content

Add/improve documentation for typing function components with access to children #3122

Description

@svdHero

With the introduction of React Hooks, the documentation recommends using function components instead of class components in the future.

However, I wonder how to define and type the component's properties when I want to access children components. I have come up with this solution (I am using Typescript):

import * as React from "react";
import "./styles.css";

type MyWrapperCompProps = {
  color: string;
  children?: React.ReactNode;
};

function MyWrapperComp(props: MyWrapperCompProps) {
  return <div style={{ backgroundColor: props.color }}>{props.children}</div>;
}

export default function App() {
  return (
    <div className="App">
      <MyWrapperComp color="tan">
        <h1>Hello World!</h1>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Porro, fuga.
        </p>
      </MyWrapperComp>
    </div>
  );
}

Edit distracted-sunset-qgwpo

This seems to work, but I have a couple of questions:

  1. Is this the best practice to model wrapper components with children?
  2. Is ReactNode the correct, most general type for children?
  3. How does React automagically know that the children are assigned to props.children? Is this hardwired to the name children or is there anything I should be aware of?
  4. Is the above documented anywhere at all on the React website?

Thanks a lot in advance for your help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions