Passing Children props into React TypeScript Component using Nx

Ye Min Ko
Learn React
Published in
3 min readJul 25, 2023
Photo by Glen Carrie on Unsplash

Prerequisites

  • Make sure you have installed Node.js version 16+.
  • To follow along with this article, you’ll need a react project that is generated with Nx. If you haven’t done it yet, see this article.

You can still follow the article by creating components in your own way.

Create Header Component

Let’s create a header component that holds children props. Run the following command.

nx g c header --dir app/components

Open header.tsx and write the following code.

Header Component

At line number 2, you can see the type React.ReactElement which expects to receive a JSX Element. Which means when you want to pass a component as a child element you can use this type.

Create SubHeader Component

Create another component called SubHeader. You can create it with the following command.

nx g c sub-header --dir app/components

Open sub-header.tsx and write the following code.

SubHeader Component

Nothing special, we just return a paragraph element. Finally, we need to call from the App component.

Call from App Component

Open app.tsx and write this code.

App Component

We passed the SubHeader component into the Header component as children props.

Serve the Application

Run with nx serve and see the result.

Passing other types as children props

If your component wants to accept string type as children props, you can achieve it like this. Change Header component as below.

Header Component

And then, open app.tsx and change the code.

App Component

Done

By using this way, we can define the type that we want to accept as children props.

--

--

Ye Min Ko
Learn React

🌐 Web Developer | 👀 Self-Learner | 👨‍💻 An Introvert