reactjs / reactjs/react.dev

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

Open
#3,122 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the TypeScript wrapper-component example in this issue and review the React website's existing documentation for function components and children. Identify the appropriate documentation entry point, then ensure the relevant guidance answers the four questions about typing, ReactNode, props.children, and whether the behavior is documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.