How to pass a React component as prop with TypeScript

Do you need to pass a React component down as a prop to a child component in TypeScript?

Let’s see how you can do this.

Best solution

Use React.ReactNode to accept everything.


interface ParentCompProps {
  childComp?: React.ReactNode;
}

const ChildComp: React.FC = () => <h2>This is a child component</h2>

const ParentComp: React.FC<ParentCompProps> = (props) => {
  const { childComp } = props;
  return <div>{childComp}</div>;
};

function App() {
  return (
    <>
      <ParentComp childComp={<ChildComp />} />
      <ParentComp childComp={<h3>Child component 2</h3>} />
      <ParentComp childComp={(
        <div style={{border: '2px solid red'}}>
          <h4>Child component</h4>
          <p>With multiple children</p>
        </div>
      )} />
    </>
  );
}

React.ReactNode is the best choice because it returns set of all possible return values of a component.

Mediocre solutions


interface ChildrenExampleProps {
  // Okay. Doesn't accept functions
  children1: JSX.Element | JSX.Element[];

  // Doesn't allow: <Comp childComp={<ChildComp />} />
  // Only allows: <Comp childComp={ChildComp} />
  // This may be a problem when you only want to pass HTML instead of
  // React component.
  children2: React.ReactType;

  // Better
  children3: React.ReactChild[];
}

Oh wow, you’ve made it this far! If you enjoyed this article perhaps like or retweet the thread on Twitter:

I like to tweet about React and post helpful code snippets. Follow me there if you would like some too!