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.

First, if you’re looking to become an expert React developer for 2021, you might want to look into Wes Bos, Advanced React course for just $97.00 (30% off). This course does a great job getting past difficult learning hurdles and giving you the skills and confidence to create amazing web applications.

Get started with Advanced React course.

Disclaimer: The two React course links are affiliate links where I may receive a small commission for at no cost to you if you choose to purchase a plan from a link on this page. However, these are merely the course I fully recommend when it comes to becoming a React expert.

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:

First, if you’re looking to become an expert React developer for 2021, you might want to look into Wes Bos, Advanced React course for just $97.00 (30% off). This course does a great job getting past difficult learning hurdles and giving you the skills and confidence to create amazing web applications.

Get started with Advanced React course.

Disclaimer: The two React course links are affiliate links where I may receive a small commission for at no cost to you if you choose to purchase a plan from a link on this page. However, these are merely the course I fully recommend when it comes to becoming a React expert.

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