How to type purely functional React wrapper component with access to children

Viewed 55

With the introduction of React Hooks, the creators of React recommend using function 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:

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?
  2. Is ReactNode the correct type for children?
  3. How does React automagically know that the children are assigned to props.children?
  4. Is the above documented anywhere at all on the React website?
0 Answers
Related